下面的简单代码产生 RangeError: Maximum call stack size exceeded
const arr = []
for (let i = 0; i < 135000; i++) {
arr.push(i)
}
const arr2 = []
// something else here that changes arr2
arr2.push(...arr)
Run Code Online (Sandbox Code Playgroud)
1)为什么会发生这种情况?(我只是将元素添加到数组中,为什么会增加堆栈大小?)
2)如何解决这个错误?(我的目标是将 arr 的浅拷贝创建到 arr2 中)
Dan*_*ger 14
那里的扩展运算符将原始数组中的所有元素推入堆栈,就像.apply:
const arr = [];
for (let i = 0; i < 10; i++) {
arr.push(i);
}
const arr2 = [];
// Something else here that changes arr2:
arr2.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Array.prototype.push.apply(arr2, arr);
console.log(arr2.join(', '));Run Code Online (Sandbox Code Playgroud)
因此,在这两种情况下可以处理的数据量都受到堆栈大小的限制:
const arr = [];
for (let i = 0; i < 135000; i++) {
arr.push(i);
}
const arr2 = [];
// Something else here that changes arr2:
arr2.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Array.prototype.push.apply(arr2, arr);
console.log(arr.length, arr2.length);Run Code Online (Sandbox Code Playgroud)
你可以这样做:
const arr = [];
for (let i = 0; i < 135000; i++) {
arr.push(i);
}
let arr2 = [];
// Something else here that changes arr2:
arr2.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
arr2 = [...arr2, ...arr];
console.log(arr.length, arr2.length);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1092 次 |
| 最近记录: |