RangeError:array.push(...)超出了最大调用堆栈大小

时间:2020-05-11 22:36:54

标签: javascript

下面的简单代码产生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)

1)为什么会发生这种情况? (我只是在数组中添加元素,为什么它会增加堆栈大小?)

2)如何解决此错误? (我的目标是将arr的浅表副本创建到arr2中)

2 个答案:

答案 0 :(得分:1)

pushes all elements in the original array into the stackjust like .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(', '));

因此,两种情况下可以处理的数据量都受堆栈大小的限制:

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);

您可以改为这样做:

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);

答案 1 :(得分:0)

//I hope this will help you to make shallow copy of arr into arr2

let arr = []
for (let i = 0; i < 135000; i++) {
    arr.push(i)
}
let arr2 = []
// something else here that changes arr2
arr2=arr

console.log(arr2[0],arr[0]);
//Both 0,0
arr[0]=100

console.log(arr[0],arr2[0])

//Both 100,100