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

19,079

Solution 1

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

Solution 2

Programmatically, you simply "push" an item in the array:

var arr = [];

arr.push("a");
arr.push("b");

arr[0]; // "a";
arr[1]; // "b"

You cannot do what you're suggesting:

arr[] = 1

is not valid JavaScript.

Solution 3

For special cases You can use next (without .push()):

var arr = [];
arr[arr.length] = 'foo';
arr[arr.length] = 'bar';

console.log(arr); // ["foo", "bar"]
Share:
19,079
user782104
Author by

user782104

php

Updated on July 29, 2022

Comments

  • user782104
    user782104 almost 2 years

    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