Demo: Add Elements to a JavaScript Array

Enter a value and select Add. Each value is appended to the end of the array with push(), and the current indexes and total length are displayed below.

The array is empty.

JavaScript Used in the Demo Top ↑

const data = [];

function addValue(value) {
  data.push(value);
  console.log(data.length, data);
}

The live version renders each value with textContent rather than building HTML from user input.

Do Not Use an Array as a General Key-Value Object Top ↑

The original demo also assigned string keys such as my_ans["key1"]. JavaScript allows extra properties on an array object, but those properties are not normal array elements and do not increase length.

const values = [];
values["key1"] = "value1";

console.log(values.length); // 0
console.log(values.key1);   // value1

If you need named key-value pairs, use a plain object or Map instead.

const answers = {
  key1: "value1",
  key2: "value2"
};

for (const [key, value] of Object.entries(answers)) {
  console.log(key, value);
}

getElementById() and Forms Array length Add and Remove Elements with splice() Demo Display Array Elements push() Tutorial




Subscribe to our YouTube Channel here



plus2net.com







anjel

07-03-2015

hi..
useful code.but i have a doubt what if i want to display particular element of any index and that index value is to be taken by entering values though users.
smo

13-03-2015

You can display the value by reading the key of the array. In side the function you can see one for loop is used with variable i, if i value is taken from user then the corresponding value can be displayed.
Himari Biswas

20-01-2016

thank u very much finally my problem solved
mr red

21-02-2017

how about, if the data in the arrays are on the table? what will the code format is?
smo1234

23-02-2017

You have to first collect the data from the table by using any server side script and SQL.

While displaying the data you can use the array push to insert data to the JavaScript array. Note that while using server side script you have to echo or print the client side JavaScript code to store values inside array.

17-04-2021

Thank you so much. This will help me



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer