简体   繁体   English

Array.push() 函数的替代代码

[英]Alternative code for Array.push() function

I've been told not to use push in my coursework, as we are only allowed to use code we have been taught, which I find ridiculous.我被告知不要在我的课程中使用推送,因为我们只能使用我们教过的代码,我觉得这很荒谬。

I have written over 200 lines of code incorporating the push function multiple times.我已经多次编写了 200 多行包含推送功能的代码。 Is there a simple code alternative to the push function which I can implement for it?是否有一个简单的代码替代我可以为它实现的推送功能?

If you need to push element to the next index in the array, use:如果需要将元素推送到数组中的下一个索引,请使用:

var arr = [];
arr[arr.length] = "something";
//output: arr = ["something"]

If you need to add element in specific index use:如果您需要在特定索引中添加元素,请使用:

var arr = [];
arr[3] = "something";
//output: arr = [undefined,undefined,undefined,"something"]

最接近的等价物

arr[arr.length] = value; 

Nowadays you can use array destructuring:现在你可以使用数组解构:

 let theArray = [1, 2, 3, 4, 5]; theArray = [ ...theArray, 6, ]; console.log(theArray);

If you want to push several elements, put them at the end of the array.如果要推送多个元素,请将它们放在数组的末尾。 You can even put elements at the beginning of the array:您甚至可以将元素放在数组的开头:

 let theArray = [1, 2, 3, 4, 5]; theArray = [ -1, 0, ...theArray, 6, 7, 8, 9, 10 ]; console.log(theArray);

The doc about it:关于它的文档:

MDN Destructuring Assignment MDN 解构赋值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM