Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new value to an existing array in JavaScript [duplicate]

In PHP, I'd do something like:

$array = array(); $array[] = "value1"; $array[] = "value2"; $array[] = "value3"; 

How would I do the same thing in JavaScript?

like image 597
Andrew Avatar asked Jan 03 '10 23:01

Andrew


People also ask

How do you add values to an existing array?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you update an array with new values?

To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values. Copied! const arr = ['zero', 'one', 'two']; arr.


Video Answer


2 Answers

You don't need jQuery for that. Use regular javascript

var arr = new Array(); // or var arr = []; arr.push('value1'); arr.push('value2'); 

Note: In javascript, you can also use Objects as Arrays, but still have access to the Array prototypes. This makes the object behave like an array:

var obj = new Object(); Array.prototype.push.call(obj, 'value'); 

will create an object that looks like:

{     0: 'value',     length: 1 } 

You can access the vaules just like a normal array f.ex obj[0].

like image 169
David Hellsing Avatar answered Oct 09 '22 15:10

David Hellsing


This has nothing to do with jQuery, just JavaScript in general.

To create an array in JavaScript:

var a = []; 

Or:

var a = ['value1', 'value2', 'value3']; 

To append values on the end of existing array:

a.push('value4'); 

To create a new array, you should really use [] instead of new Array() for the following reasons:

  • new Array(1, 2) is equivalent to [1, 2], but new Array(1) is not equivalent to [1]. Rather the latter is closer to [undefined], since a single integer argument to the Array constructor indicates the desired array length.
  • Array, just like any other built-in JavaScript class, is not a keyword. Therefore, someone could easily define Array in your code to do something other than construct an array.
like image 40
Mike Avatar answered Oct 09 '22 16:10

Mike