JavaScript数组遍历的问题及解决方案

前言

在刚接触 JavaScript 的数组时,就曾怀疑 JavaScript 中的 数组的遍历 和 迭代 相关的方法(如:every()filter()find()findIndex()forEach() 等等)都是非安全、和非严谨的,现在终于决定研究一下,事实果真如此,以下是我的研究成果,分享于大家;

目录

一、数组遍历的等效逻辑
二、数组遍历的问题
三、迭代的问题
四、解决方案

内容

一、数组遍历的等效逻辑

JavaScript数组有很多遍历相关的方法,如:every()filter()find()findIndex()forEach() 等等;

通过测试、分析得出:
这些方法的遍历逻辑都是一样的,以 forEach() 为例,其它遍历的等效逻辑如下:

forEach的语法:

array.forEach(function handle(currentValue, index, arr), thisValue)

等效逻辑:

Array.prototype.forEach = function (handle, thisValue) {

    if (thisValue == null) {
        thisValue = window;
    }

    var oriLength = this.length;
    for (var index = 0; index < Math.min(this.length,oriLength); index++) {
        handle.call(thisValue, this[index], index, this);
    }

}

所以就有如下的数组遍历特性:

数组遍历特性:

  • 特性1: handle 的 arr 参数始终是被遍历的数组的最新状态时的值;
  • 特性2: handle 的 index 参数始终是递增的;
  • 特性3: handle 的 index 参数会增加到 minLength - 1 ,minLength 是 被遍历的数组的初始 length 与 被遍历的数组的阿最新 length 的最小值;
  • 特性4: handle 的 currentValue 参数始终是被遍历的数组的最新状态时 索引为 index 的元素的值;

二、数组遍历的问题

正因为如此,当在 handle 中对被遍历的数组进行增加 或者 删除元素时,会有使数组的遍历 重复 或者 漏掉 遍历数些元素;
如下:

问题1:漏掉某些元素

示例::

var gby = ["a","b","c","d","e","f"];

gby.forEach(function (item,index,arr) {
    
    console.log("item:",item,"index:",index,"arr:",arr,"this:",this);

    if (index == 2){
        //删除2个元素
        arr.splice(index,2);
    }

});

结果:

漏掉元素示例结果

从代码运行结果中可以看出,元素 de 被漏掉了;

原因:
在当 index == 2 时,把 index 为 2 及其后的一个元素给删除了,即删除了 cd ,这时,ef 分别成了 index 为 2 和 3 的元素;然而由于 index 参数始终是递增的,所以,当下次 index 变为 3 时,就跳过了 de 而遍历了 f

问题2:重复遍历某些元素

示例::

var gby = ["a","b","c","d","e","f"];

gby.forEach(function (item,index,arr) {
    
    console.log("item:",item,"index:",index,"arr:",arr,"this:",this);

    if (index == 2){
        //添加元素
        arr.splice(index,0,"g");
    }

});

结果:

重复元素示例结果

从代码运行结果中可以看出,元素 c 被重复遍历了,而 元素 f 被漏掉了;

原因:
在当 index == 2 时遍历了元素 c,并且在 index 为 2 处插入了元素 g,当 g 被插入后,元素 c 侧被挤到了 index 为 3 的地方,同样,元素 c 后面的元素都往后移了一位,所以此时元素 f 的 index 为 6;当下次 index 增长为 3 时,则又把 元素 c 给遍历出来了,所以 元素 c 被重复遍历了;又因为被遍历的数组中添加了新元素,所以被遍历的数组的 length 增加了,根据数组的遍历特性4(handle 的 index 参数会增加到 minLength - 1 ,minLength 是 被遍历的数组的初始 length 与 被遍历的数组的阿最新 length 的最小值;)可知,index 只会增强到 5 ,所以,index 为 6 的元素 f 不会再被遍历了,就导致漏掉了 元素 f

问题总结

  • 在遍历数组的过程中删除被遍历数组元素的行为会导致漏掉遍历某些元素;
  • 在遍历数组的过程中往被遍历数组中插入元素的行为会导致重复遍历某些元素 和 漏掉遍历被遍历数组尾部的元素;

三、迭代的问题

跟数组遍历一样,迭代器的迭代过程也有像数组一样的问题,所以,当用 for...of 或者 在迭代过程中对迭代对象进行增、删、移位等操作时也会有漏掉 或者 重复 迭代某些元素的情况;

四、解决方案

造成这个问题的原因就是在遍历数组的过程中在被遍历的数组中删除 或者 插入了元素,从而导致被遍历的数组的中元素的 index 索引 和 被遍历数组的 length 变化,进而导致 漏遍历 和 重复遍历某些元素;

所以,解决方案的思路是:

解决思路

  1. 先生成一份被遍历的 数组 或者 元素集 array 的副本 arrayCopy;
  2. 然后对 arrayCopy 进行遍历,对遍历得到的元素 item 通过 array.indexOf(item) 获得 item 在 array 中的索引;

为了满足各种场景的需求,根据该思路,我抽离并封装了以下几种实现:

实现1:safelyFilter(operation, thisValue)

/**
 * safelyFilter(operation, thisValue)
 * 安全地操作并过滤所有元素;与 forEach 和 filter 的区别是: safelyFilter 能保证会遍历数组中所有已存在的元素,不会受 operation 中的行为的影响;
 * @param operation : (currentValue,currentIndex,currentArray)=>boolean | undefined     执行的操作, 该函数的返回值表示是否要过滤出该元素
 * @param thisValue ? : any   可选,默认值是被操作的数组,即调用者;操作 operation 的 this 值
 * @returns [Item]  返回被 operation 过滤出的元素
 *
 *
 * operation(currentValue,currentIndex,currentArray)=>boolean | undefined
 * @param currentValue : any   调用 operation 时的元素的值;
 * @param currentIndex : number     调用 operation 时 currentValue 对应的最新状态的索引值;
 * @param currentArray : Array   调用 operation 时 被操作时最新状态的数组;
 * @returns boolean | undefined  表示是否要过滤出 currentValue ;
 *
 */
Array.prototype.safelyFilter = function (operation, thisValue) {

    if (thisValue == undefined) {
        thisValue = this;
    }

    let arrayCopy = this.slice();
    let filterItem = arrayCopy.filter((currentValue) => {
        let currentIndex = this.indexOf(currentValue);
        operation.call(thisValue, currentValue, currentIndex, this);
    });


    return filterItem;

}

实现2:safelyOperateIndexs(indexList, operation, thisValue)

/**
 * safelyOperateIndexs(indexList, operation, thisValue)
 * 安全操作指定的索引
 * @param indexList : [Index]   需要被操作的索引数组
 * @param operation : (currentValue,currentIndex,currentArray)=>Void     执行的操作
 * @param thisValue ? : any   可选,默认值是被操作的数组,即调用者;操作 operation 的 this 值
 * @returns [Item]   被操作的元素列表
 *
 *
 * operation(currentValue,currentIndex,currentArray)=>Void
 * @param currentValue : any   调用 operation 时的元素的值;
 * @param currentIndex : number     调用 operation 时 currentValue 对应的最新状态的索引值;
 * @param currentArray : Array   调用 operation 时 被操作时最新状态的数组;
 *
 */
Array.prototype.safelyOperateIndexs = function (indexList, operation, thisValue) {

    if (thisValue == undefined) {
        thisValue = this;
    }

    let itemList = this.filter(function (currentValue, index) {
        return indexList.includes(index);
    });


    itemList.forEach((currentValue) => {
        let currentIndex = this.indexOf(currentValue);
        operation.call(thisValue, currentValue, currentIndex, this);
    });

    return itemList;

}

实现3:safelyOperateItems(itemList, operation, thisValue)

/**
 * safelyOperateItems(itemList, operation, thisValue)
 * 安全操作指定的元素
 * @param itemList : [Item]   需要被操作的元素的数组
 * @param operation : (currentValue,currentIndex,currentArray)=>Void     执行的操作
 * @param thisValue ? : any   可选,默认值是被操作的数组,即调用者;操作 operation 的 this 值
 * @returns [Index]   被操作的元素的索引的列表;
 *
 *
 * operation(currentValue,currentIndex,currentArray)=>Void
 * @param currentValue : any   调用 operation 时的元素的值;
 * @param currentIndex : number     调用 operation 时 currentValue 对应的最新状态的索引值;
 * @param currentArray : Array   调用 operation 时 被操作时最新状态的数组;
 *
 */
Array.prototype.safelyOperateItems = function (itemList, operation, thisValue) {

    if (thisValue == undefined) {
        thisValue = this;
    }


    let itemListCopy = [];
    let indexList = itemList.map((item) => {
        itemListCopy.push(item);
        return this.indexOf(item);
    });

    itemListCopy.forEach((currentValue) => {
        let currentIndex = this.indexOf(currentValue);
        operation.call(thisValue, currentValue, currentIndex, this);
    });

    return indexList;

}

实现4:针对迭代的实现:safelyIterate(iterable,operation, thisValue)

/**
 * safelyIterate(iterable,operation, thisValue)
 * 对 iterable  进行安全的迭代;与 for...of 的区别是:safelyIterate 能保证会迭代过程不会受 operation 中的行为的影响从而迭代每一个元素;
 * @param iterable : Iterable   必选; 可迭代的对象;
 * @param operation : (currentValue,currentIndex,iterable)=>boolean | undefined     执行的操作, 该函数的返回值表示是否要过滤出该元素
 * @param thisValue ? : any   可选,默认值是 iterable ;操作 operation 的 this 值
 * @returns [Item]  返回被 operation 过滤出的元素
 *
 *
 * operation(currentValue,currentIndex,iterable)=>boolean | undefined
 * @param currentValue : any   调用 operation 时的元素的值;
 * @param currentIndex : number     currentValue 在原始 iterable 中 对应的迭代索引值;
 * @param iterable : Iterable   被迭代的 iterable ;
 * @returns boolean | undefined  表示是否要过滤出 currentValue ;
 *
 */
window.safelyIterate = function safelyIterate(iterable,operation, thisValue) {

    if (thisValue == undefined) {
      thisValue = iterable;
    }

    let arrayCopy = [];

    for (let value of iterable){
      arrayCopy.push(value);
    }

    let filterItem = arrayCopy.filter(function (currentValue) {
      let currentIndex = this.indexOf(currentValue);
      operation.call(thisValue, currentValue, currentIndex, iterable);
    },arrayCopy);


    return filterItem;

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容