Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new value to the end of an numerical array? [duplicate]

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?

like image 333
ajsie Avatar asked Dec 25 '09 16:12

ajsie


2 Answers

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"]
like image 101
Pascal MARTIN Avatar answered Sep 29 '22 11:09

Pascal MARTIN


You can use

arrayName.push('yourValue');

OR

arrayName[arrayName.length] = 'yourvalue';

Thanks

like image 22
Mahesh Velaga Avatar answered Sep 29 '22 12:09

Mahesh Velaga