简体   繁体   English

javascript forEach数组回调时间?

[英]javascript forEach array callback timing?

So im learning about the different array iterating methods and ran into something odd: 所以我学习了不同的数组迭代方法,并遇到了奇怪的事情:

[1,2,3].forEach(function(element,index,arr){
        console.log(element,index);
    console.log(arr);
    arr.shift();
})

So you would think this would produce: 因此,您会认为这将产生:

1,0
[1,2,3]
2,1
[2,3]
3,2
[3]

however you get this: 但是你得到这个:

1 0
[1, 2, 3]
3 1
[2, 3]

Im printing off 3 despite have only shifted off at the end? 我只打印了3,尽管最后只关闭了? Is this because the arr callback happens at the beginning of the next item or something? 这是因为arr回调发生在下一项或其他内容的开头吗? Since it should be doing shift() on the array AFTER? 由于它应该在数组之后执行shift()? I realize this is a "bad case" of using this method, im just curious why this happens. 我意识到这是使用此方法的“坏案例”,只是很好奇为什么会发生这种情况。

The .length of the array is changed. 数组的.length已更改。 The element adjacent to element at index 0 becomes index 0 following .shift() call. 在调用.shift()之后,与索引0处的元素相邻的元素将变为索引0

The answer to your question is described in the documentation of shift method. 在shift方法的文档中描述了您问题的答案。

As per MDN from here 根据MDN从这里

The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. shift方法删除零位索引处的元素,并将连续索引处的值向下移位,然后返回删除的值。 If the length property is 0, undefined is returned. 如果length属性为0,则返回undefined。

So, once the shift operation is done the Original array is changed from [1,2,3] to [2,3] and the value of index increments from 0 to 1 . 因此,完成移位操作后,原始数组从[1,2,3]更改为[2,3] ,索引值从0递增至1 Next, iteration the third iteration of the loop is Not required as the length of the array (2) has been traversed. 接下来, 不需要循环的第三次迭代,因为已经遍历了数组(2)的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM