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
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
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