19

In PHP I can do like:

$arrayname[] = 'value';

Then the value will be put in the last numerical key eg. 4 if the 3 keys already exists.

In JavaScript I can’t do the same with:

arrayname[] = 'value';

How do you do it in JavaScript?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
ajsie
  • 77,632
  • 106
  • 276
  • 381

3 Answers3

12

You can use the push method.


For instance (using Firebug to test quickly) :

First, declare an array that contains a couple of items :

>>> var a = [10, 20, 30, 'glop'];

The array contains :

>>> a
[10, 20, 30, "glop"]


And now, push a new value to its end :

>>> a.push('test');
5

The array now contains :

>>> a
[10, 20, 30, "glop", "test"]
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • To add multiple elements at the same time or to add an element somewhere other than the end check out the answer: http://stackoverflow.com/a/12189963/984780 – Luis Perez Aug 30 '12 at 04:52
  • Just to help other rookies who come along, do NOT try `a = a.push('test');` for 10 mins. :) – Joshua Dance May 14 '14 at 16:51
11

You can use

arrayName.push('yourValue');

OR

arrayName[arrayName.length] = 'yourvalue';

Thanks

Mahesh Velaga
  • 21,633
  • 5
  • 37
  • 59
7

You can use array push method

arrayname.push('value');
Chandra Patni
  • 17,347
  • 10
  • 55
  • 65