25 Feb JavaScript Arrays
Array is a collection of similar types of elements. The JavaScript Array object represents such an array.
Note: We have used the const keyword to create an array since it is generally and widely preferred. The cost introduced in ES6.
Create an Array
Let us see how to create an array in JavaScript. We have created an array of string elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="test"></p> <script> const product = ["Table", "Chair", "Shelves", "Bookcases"]; document.getElementById("test").innerHTML = product; </script> </body> </html> |
Output
Access Array elements
To access elements in an array, we use the square brackets. Within that, set the index number. Like Java, the arrays in JavaScript begin with index 0. Therefore, the following access the 1st element from the product array:
1 2 3 |
product[0] |
Let us see an example to access array elements in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <p id="test"></p> <script> const product = ["Table", "Chair", "Shelves", "Bookcases"]; document.getElementById("test").innerHTML = "<p><strong>Product1 = </strong>"+product[0]+"</p><p><strong>Product2 = </strong>"+product[1]+"</p>"; </script> </body> </html> |
Output
Find the length of an array
To find the length of an array in JavaScript, use the length property. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <p id="test"></p> <script> const product = ["Table", "Chair", "Shelves", "Bookcases"]; document.getElementById("test").innerHTML = product.length; </script> </body> </html> |
Output
Iterate an Array
To iterate an array in JavaScript, we will use the for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <p id="test"></p> <script> const product = ["Table", "Chair", "Shelves", "Bookcases"]; let res = "<p>"; for (let i = 0; i < product.length; i++) { res += "<strong>Product "+(i+1)+" = </strong>"+ product[i] + "<br />"; } res += "</p>"; document.getElementById("test").innerHTML = res; </script> </body> </html> |
Output
No Comments