Is there a shorthand way to auto increment a Javascript array like you can in PHP?
PHP Example:
$myArray=[];
$myArray[] = [ 'item1' , 'item2' ];
$myArray[] = [ 'item3' , 'item4' ];
JS Example:
let myArray = [];
myArray[ myArray.length ] = [ 'item1' , 'item2' ];
myArray[ myArray.length ] = [ 'item3' , 'item4 '];
//or
myArray.push( [ 'item1' , 'item2' ] );
myArray.push( [ 'item3' , 'item4' ] );
Without using myArray.length or myArray.push()
Here is the ES6 way, using spread operator
const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = [...arr1, ...arr2]; // arr3 ==> [1,2,3,3,4,5]
OR
just by using the concat method
const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = arr1.concat(arr2); // arr3 ==> [1,2,3,3,4,5]
Beside the given answers, you could use Array#splice with a great value for adding the values to the end of the array.
var array = [];
array.splice(Infinity, 0, ...['item1', 'item2']);
array.splice(Infinity, 0, ...['item3', 'item4']);
console.log(array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With