【问题标题】:RangeError: Maximum call stack size exceeded with array.push(...)RangeError:array.push(...) 超出了最大调用堆栈大小
【发布时间】:2020-05-11 22:36:54
【问题描述】:

下面的简单代码产生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) 如何解决这个错误? (我的目标是在 arr2 中创建 arr 的浅拷贝)

【问题讨论】:

标签: javascript


【解决方案1】:

那里的传播运算符pushes all elements in the original array into the stack, just 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);

【讨论】:

    【解决方案2】:

    //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

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2017-07-02
      • 2020-11-19
      • 2013-08-23
      • 2021-09-07
      • 2017-11-12
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多