我被告知不要在我的类(class)中使用推送,因为我们只被允许使用我们学过的代码,我觉得这很荒谬。
我已经多次编写了 200 多行包含 push 功能的代码。是否有一个简单的代码替代我可以实现的推送功能?
最佳答案
现在你可以使用数组解构:
let theArray = [1, 2, 3, 4, 5];
theArray = [
...theArray,
6,
];
console.log(theArray);
如果要推送多个元素,请将它们放在数组的末尾。您甚至可以将元素放在数组的开头:
let theArray = [1, 2, 3, 4, 5];
theArray = [
-1,
0,
...theArray,
6,
7,
8,
9,
10
];
console.log(theArray);
关于它的文档:
MDN Destructuring Assignment
关于javascript - Array.push() 函数的替代代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33545053/