大家好,stackoverflow 社区的好人。我被困在一个硬件问题上,希望你能帮助我。
// 5. Write the code that would make this test pass.
// describe("multTwo", () => {
// test ("returns an array with all the numbers multiplied by two", () => {
// expect(multTwo([3, 4, 5])).toEqual([6, 8, 10])
// expect(multTwo([23, -9, 0])).toEqual([46, -18, 0])
// expect(multTwo([4.5, -4.5, 12])).toEqual([9, -9, 24])
// })
// })
let friendlyArray = [1,2,3,4,5]
let newArr = []
const multTwo = (arr) => {
for (let i = 0; i < arr.length; i++)
arr.push(newArr[i] *2 )
return arr;
};
console.log(multTwo(friendlyArray))
我正在尝试将一个数组传递给一个新数组,其中前一个数组中的所有数字都已乘以 2。
当我运行程序(使用 AWS 上的节点)时,我的环境内存不足,它会杀死所有进程。
最佳答案
当你插入数组时,它的长度会增加。所以如果原来的长度是5,经过一次迭代,新的长度是6。经过第二次迭代,新的长度是7。所以
for (let i = 0; i < arr.length; i++)
将永远循环。
使用 .map
代替,它是基于在每个元素上运行的回调函数将一个数组转换为另一个数组的最合适的方法:
const multTwo = arr => arr.map(num => num * 2);
let friendlyArray = [1,2,3,4,5]
console.log(multTwo(friendlyArray))
关于javascript - 使用 arr.push 会导致我的程序崩溃吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549205/