在JavaScript中,foreach方法是否会创建数组的副本?

huangapple go评论76阅读模式
英文:

Does the foreach method create a copy of the array on which it is launched is JS?

问题

I think in some cases it is, but not in others.

The following JS code does not produce an infinite loop, I deduce that foreach creates a copy of the array when called

var li = [""]
li.forEach(() => {
    li.push("");
});

But the following code return "1 2 3 AA 5". Which shouldn't be the case if he had created a copy of the array. So why?

var li2 = [1,2,3,4,5]
li2.forEach((el) => {
    li2[3] = "AA";
  console.log(el)
});

Ty

英文:

I think in some cases it is, but not in others.

The following JS code does not produce an infinite loop, I deduce that foreach creates a copy of the array when called

var li = [""]
li.forEach(() => {
    li.push("");
});

But the following code return "1 2 3 AA 5". Which shouldn't be the case if he had created a copy of the array. So why?

var li2 = [1,2,3,4,5]
li2.forEach((el) => {
    li2[3] = "AA";
  console.log(el)
});

Ty

答案1

得分: 1

"Does the foreach method create a copy of the array on which it is launched is JS?"

不,它不会。它会迭代原始数组的初始范围。如果在迭代过程中数组的范围/大小发生变化,它不会影响forEach的迭代。

这类似于以下示例代码:

function forEach(arr, cb) {
  for (let idx = 0, len = array.length; idx < len; ++idx) {
    cb(array[idx], idx, array);
  }
}

const array = [1, 2, 3];

forEach(array, (el, idx) => {
  array.push(el + idx);
});
console.log(array);

但实际的实现还会跳过稀疏数组中的空槽位。

英文:

"Does the foreach method create a copy of the array on which it is launched is JS?"

No, it doesn't. It iterates over the initial range of the original array. If the range/size of the array changes while iterating, it doesn't influence the iteration of the forEach.

It's similar to

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function forEach(arr, cb) {
  for (let idx = 0, len = array.length; idx &lt; len; ++idx) {
    cb(array[idx], idx, array);
  }
}

const array = [1, 2, 3];

forEach(array, (el, idx) =&gt; {
  array.push(el + idx);
});
console.log(array);

<!-- end snippet -->

but the actual implementation also skips empty slots in sparse arrays.

huangapple
  • 本文由 发表于 2023年5月7日 02:31:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定