用递归的方式处理数组 && 把递归方法方法定义到数组的原型上

在 javascript 里,如果我们想用一个函数处理数组 (Array) 中的每个元素,那我们有很多种选择,最简单的当然就是用自带的 forEach 函数(低版本也可以使用 lodash 中的 forEach 函数):

const arr = [0,1,2,3,4,5,6,7,8,9];
 
arr.forEach(item=>{ console.log(item) });//依次输出

 除了这种遍历,数组还有一种很常用的操作,就是拿来递归,js中的数组自带了 pop 和 push 方法,其实也可以当作一个链表来用,配合递归自然也是相当好用:

const arr = [0,1,2,3,4,5,6,7,8,9];
 
const func = (arr)=>{
    item = arr.pop();
    console.log(item);
    if (arr.length==0) return;
    return func(arr);
}
func(arr)

 这样也能实现和之前 forEach 类似的效果~
既然效果差不多,那我们为啥要搞出这么麻烦的东西??
嘛……有些场景下遍历操作也不是那么好用的啦……比如我以前博文中写到的那个爬虫

"use strict"
const request = require('request')
const fs = require('fs')
 
const arr = [
    'http://path.to/img1.jpg',
    'http://path.to/img2.jpg',
    'http://path.to/img3.jpg',
    ...
    'http://path.to/img498.jpg',
    'http://path.to/img499.jpg',
    'http://path.to/img500.jpg'
]
 
arr.forEach(src=> {
    //下载图片
    const ws = fs.createWriteStream('./download/'+src.split('/').pop());
    ws.on('close', ()=>{
        console.log('下载完成')
    })
    request(src).pipe(ws);
})

 因为 request 是一个异步操作,所以它并不会阻塞 forEach ,也就是说上面这个 demo 一旦运行起来,就会创建500个并发的网络请求和文件写入……
这就不太好玩了,一般来说并发请求可以提高网络利用效率,但效率再怎么提高,带宽也是有限的,并发过多就会导致单个请求变慢,请求过慢就可能会被服务端干掉,被服务端干掉的话我们就拿不到想要的图片了

所以我们期望的效果是依次执行下载操作,下载完一个再去下载另一个,这时候就比较适合用递归了~

"use strict"
const request = require('request')
const fs = require('fs')
 
const arr = [
    'http://path.to/img1.jpg',
    'http://path.to/img2.jpg',
    'http://path.to/img3.jpg',
    ...
    'http://path.to/img498.jpg',
    'http://path.to/img499.jpg',
    'http://path.to/img500.jpg'
]
 
const download = (arr)=>{
    src = arr.pop();
    //下载图片
    const ws = fs.createWriteStream('./download/'+src.split('/').pop());
    ws.on('close', ()=>{
        console.log('下载完成')
        if (arr.length>0)
            return download(arr);
    })
    request(src).pipe(ws);
}
download (arr);

 这样我们就可以依次下载图片啦~
可是既然是经常会用的东西……有没有更方便的用法啊,就像forEach那样的……?
那把递归这个操作抽象出来,直接定义到数组的原型 (prototype) 上吧

Array.prototype.recursion = function (func) {
    const re = function (arr) {
        if (!arr.length) return;
        const item = arr.pop();
        return func(item, function () {
            return re(arr);
        });
    }
    re(this);
}

 于是乎这样随便写了一下,虽然很简陋,但好歹是可以用的, 使用方式如下:

"use strict"
const request = require('request')
const fs = require('fs')
 
const arr = [
    'http://path.to/img1.jpg',
    'http://path.to/img2.jpg',
    'http://path.to/img3.jpg',
    ...
    'http://path.to/img498.jpg',
    'http://path.to/img499.jpg',
    'http://path.to/img500.jpg'
]
 
arr.recursion((src, next)=> {
    //下载图片
    const ws = fs.createWriteStream('./download/'+src.split('/').pop());
    ws.on('close', ()=>{
        console.log('下载完成');
        //当前异步操作完成后,调用next来进行下一次操作
        next()
    })
    request(src).pipe(ws);
})

 链表加递归这种做法毕竟还是更适合函数式风格,而操作原型这种做法更多的则是面向对象风格,函数式编程比较强调无副作用,而显然……我现在这种做法是有副作用的,递归过程中不断pop(),递归完成后,arr 就变成一个空数组了。
其实这也还只是一个半成品,我们可能还希望在递归完成的时候,再继续执行一些操作,比如说把下载下来的图片打个压缩包?或者发一条消息告诉我文件都下载完成了之类的。
不管怎么说,这也是一个思路,如果发现这个思路中有其他严重的问题,或者有更好的建议

下面的递归代码在数组列表偏大的情况下会导致堆栈溢出。在保留递归模式的基础上,你怎么解决这个问题?

var list = readHugeList();

var nextListItem = function() {

    var item = list.pop();

    if (item) {

        // process the list item...

        nextListItem();

    }

};

潜在的堆栈溢出可以通过修改nextListItem 函数避免:

var list = readHugeList();

var nextListItem = function() {

    var item = list.pop();

    if (item) {

        // process the list item...

        setTimeout( nextListItem, 0);

    }

};

堆栈溢出之所以会被消除,是因为事件循环操纵了递归,而不是调用堆栈。当 nextListItem 运行时,如果 item不为空,timeout函数(nextListItem)就会被推到事件队列,该函数退出,因此就清空调用堆栈。当事件队列运行其timeout事件,且进行到下一个 item 时,定时器被设置为再次调用 nextListItem。因此,该方法从头到尾都没有直接的递归调用,所以无论迭代次数的多少,调用堆栈保持清空的状态。

猜你喜欢

转载自blog.csdn.net/qq_34093387/article/details/126534927
今日推荐