Reputation: 207
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?
Upvotes: 7
Views: 31366
Reputation: 407
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:
Upvotes: 12
Reputation: 1440
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"]
Upvotes: 9