gpt4 book ai didi

javascript - 如果在使用 javascript 中的 map 方法执行遍历该数组的循环期间将元素插入数组,会发生什么情况

转载 作者:行者123 更新时间:2023-11-30 13:56:55 25 4
gpt4 key购买 nike

在我的网络应用程序中:

  • 我有一个通过 firebase API 实时更新的数组。
  • 我有一个用户触发的方法,该方法通过该数组循环到根据一些给定的参数检索元素。

如果在使用 javascript 中的 map 方法执行遍历数组的循环期间将元素插入数组,会发生什么情况?

或者换句话说,我可以假设当使用 map 方法循环遍历数组时,map 方法循环遍历数组的快照吗?

我想避免使用 JSON.parse(JSON.stringify(myArray)) 来确保循环遍历快照。

任何人都可以提供可以测试这种情况以获得明确答案的代码吗?

最佳答案

你真的不需要测试这个; The ECMAScript spec很清楚:

The range of elements processed by map is set before the first call to callbackfn. Elements which are appended to the array after the call to map begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callbackfn will be the value at the time map visits them; elements that are deleted after the call to map begins and before being visited are not visited.

如果你想测试你可以使用这样的东西:

const arr = [5];

const result = arr.map( x => {
console.log( `Visiting ${x}` );
arr.push( x + 1 );
return 2*x;
} );

console.log( arr ); // Has two elements

console.log( result ); // Only has one element

但是,当你说:

Or to put it another way, can i assume that when using the map method to loop through an array, that the map method loops through a snapshot of the array?

这与您之前的措辞不同。映射回调不会访问插入数组的元素,但已替换的元素将成为它们的新值。你可以这样测试:

const arr = [0,0];

const result = arr.map( x => {
console.log( `Visiting ${x}` );
arr[1] = 3;
return 2*x;
} );

console.log( result );

备注:Array#map是同步的,而 JavaScript 是单线程的,因此如果回调中的代码不改变数组,则数组不可能在迭代期间发生改变(其他代码,即 firebase,无法在 map 运行时运行)。

const arr = [0,1,2,3,4,5];

// Change a random value in arr every 4 milliseconds
// Emulates Firebase modifying the array
setInterval( function ( ) {
arr[~~(Math.random()*6)] = Math.random( );
}, 4 );

// (async), Logs values after they've been modified
setTimeout( function ( ) {
console.log( 'Logging array values after one second' );
arr.map( x => console.log( x ) );
}, 1000 );

// Logs the values unmodified, async code, such as Firebase can't affect this
console.log( '(sync) with a 100ms spinlock between each map callback, to demonstrate that the array cannot be modified externally during the map.' );
arr.map( x => {
console.log( x );
const start = +new Date;
while( +new Date < start + 100 ); // Wait for 100 milliseconds
} );

关于javascript - 如果在使用 javascript 中的 map 方法执行遍历该数组的循环期间将元素插入数组,会发生什么情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57085182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com