英文:
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 < len; ++idx) {
cb(array[idx], idx, array);
}
}
const array = [1, 2, 3];
forEach(array, (el, idx) => {
array.push(el + idx);
});
console.log(array);
<!-- end snippet -->
but the actual implementation also skips empty slots in sparse arrays.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论