Reputation: 37
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()
Upvotes: 3
Views: 2774
Reputation: 386560
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);
Upvotes: 1
Reputation: 2087
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]
Upvotes: 2
Reputation: 7746
There is certainly a way to do exactly the same thing; it even has similar construction:
let arr = ['a', 'b'];
arr = arr.concat([['c', 'd']]);//['a', 'b', ['c', 'd']]
PHP:
<?php
$arr = ["a", "b"];
$arr[] = ["c", "d"];
print_r($arr);
?>
Array
(
[0] => a
[1] => b
[2] => Array
(
[0] => c
[1] => d
)
)
Upvotes: 0