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.
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.
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| 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 | |