JavaScript: Add Array Elements
Question by Compi | 2015-08-10 at 22:39
Using JavaScript, you can easily specify an array, for example with "var arr = [1, 2, 3]". But what about adding some new further elements to an existing array?
Is it possible to add an element to an existing JavaScript array without re-creating the entire array? Is there any function I can use for that?
Related Topics
JavaScript: Create and Use Arrays
Info | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
JavaScript: Sort Array of Numbers
Tutorial | 0 Comments
PHP: Fill Array with Sequence of Numbers or Characters
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Yes, there is a function available for that. It is called .push() and it can be used like that:
In this example, we are creating an array consisting of the elements 1, 2 and 3. After that, we are using .push(4) to add one further element - the number 4 - to the array. This makes our new array containing the elements 1, 2, 3 and 4.
Another way, we can use to enlarge an array, is to just access an index that is not yet in use.
This example is creating the same result like it was in this first example. The elements 1, 2 and 3 do have the indices 0, 1 and 2. With setting the element with the non-existing index 3, we are accordingly extending the array.
Instead of directly hard coding the index, we can also use the property "length" of the array, which is giving us the length of the array:
With this code, we are creating an array containing the elements 1, 2, 3, 4 and 5. The array length is 3 in the second line and 4 in the third line. Therefore, by doing this, we are also adding a new element at the end of the array.
By the way, the index, we are using here, do not have to be the next available or free index. We are also free to directly access the index 10 or 100, for example, which however will result in an array containing a great number of undefined elements.
2015-08-13 at 16:48