Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Is there a simple code alternative to the push function which I can implement for it?

like image 770
James Powell Avatar asked Dec 10 '22 20:12

James Powell


1 Answers

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

like image 139
SteamFire Avatar answered Dec 26 '22 13:12

SteamFire