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
  • 620,600
  • 104
  • 758
  • 828
ajsie
  • 74,062
  • 99
  • 267
  • 376

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
  • 385,748
  • 76
  • 642
  • 654
  • 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,059
  • 5
  • 35
  • 59
7

You can use array push method

arrayname.push('value');
Chandra Patni
  • 16,977
  • 10
  • 51
  • 64