【问题标题】:es6 map if the array gets changedes6 映射如果数组被改变
【发布时间】:2021-12-29 14:34:00
【问题描述】:
window.arr = [ 1, 2, 3, 4, 5 ];
window.arr.map(el=>{
    console.log(el);
});
asyncFunction(){
    window.arr = [ 2, 4, 6 ];
}

如果 asyncFunction 碰巧在 map 仍在运行时更新数组,ma​​p 会做什么?

【问题讨论】:

  • Javascript 调用栈是单线程的,所以不会有这种情况asyncFunction happens to update the array while map is still running
  • 什么都没有。它已经运行了。
  • ……无论如何,您不是在更新数组,而是在更新arr 变量map 在一个对象上被调用,它将继续使用该对象,而不管最初查找该对象的变量发生了什么变化。
  • 除了异步之外,您可以在map 内显式更改window.arr,这不会影响调用结果。

标签: javascript arrays ecmascript-6


【解决方案1】:

首先Array.prototype.map() 是完全同步的,因此 Javascript 的单线程特性将阻止您的 asyncFunction 在您的 windows.arr.map() 运行期间运行。

但是,更有趣的是window.arr = [2,4,6]window.arr 变量分配了一个新数组。该数组与.map() 正在处理的数组毫无关系。因此,即使它们可能以某种方式交织在一起,.map() 操作也有自己的数组,它只会继续处理该数组,而该数组与放入 window.arr 属性的新数组无关。

记住这样的语句:

 window.arr = [2,4,6];

不对之前在window.arr 中的任何数组做任何事情。如果其他人引用了先前的数组,则该数组仍然存在并且不会改变。

这是一个简单的演示:

let a = [1,2,3];
let b = [4,5,6];
window.arr = a;
console.log(a);
window.arr = b;
console.log(a);

由此,您可以看到数组a 在重新分配window.arr 时根本没有改变。因此,在您的示例中,.map() 正在运行的是数组 a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 2022-01-18
    • 2019-11-21
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    相关资源
    最近更新 更多