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?

0

3 Answers 3

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

To add multiple elements at the same time or to add an element somewhere other than the end check out the answer: stackoverflow.com/a/12189963/984780
Just to help other rookies who come along, do NOT try a = a.push('test'); for 10 mins. :)
11

You can use

arrayName.push('yourValue');

OR

arrayName[arrayName.length] = 'yourvalue';

Thanks

Comments

7

You can use array push method

arrayname.push('value');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.