Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can javascript add element to an array without specifiy the key like PHP?

In PHP , I can add a value to the array like this:

array[]=1;
array[]=2;

and the output will be 0=>'1', 1=>'2';

And if I tried the same code in javascript , it return Uncaught SyntaxError: Unexpected string . So , is there any way in JS to work the same as PHP? Thanks

like image 482
user782104 Avatar asked Jan 28 '13 06:01

user782104


1 Answers

Simply use Array.push in javascript

var arr = [1,2,3,4];

// append a single value
arr.push(5);  // arr = [1,2,3,4,5]

// append multiple values
arr.push(1,2) // arr = [1,2,3,4,5,1,2]

// append multiple values as array
Array.prototype.push.apply(arr, [3,4,5]); // arr = [1,2,3,4,5,1,2,3,4,5]

Array.push on MDN

like image 96
MarcDefiant Avatar answered Oct 05 '22 23:10

MarcDefiant