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. 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.