Javascript-Arrays
An array is a single variable that is used to store various elements(hold more than one value at a time.). You want to store a list of elements and access them by a single variable.
Creating an Array:
Syntax:
var array_name = [item1, item2, ...];
Example:
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> var cars = ["html", "css", "javascript"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html>
OUTPUT:
JavaScript Arrays
html,css,javascript
3 ways to construct array in JavaScript:
- By array literal
- By creating instance of Array directly (using new keyword)
- By using an Array constructor (using new keyword)
JavaScript array literal:
syntax :
var arrayname=[value1,value2.....valueN];
values are contained inside [ ] and separated by , (comma).
Example:
<html> <body> <script> var emp=["Html","CSS","JAVASCRIPT"]; for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br/>"); } </script> </body> </html>
OUTPUT:
Html
CSS
JAVASCRIPT
JavaScript Array directly (new keyword):
syntax :
var arrayname=new Array();
new keyword is used to create instance of array.
Example:
<html> <body> <script> var i; var emp = new Array(); emp[0] = "HTML"; emp[1] = "CSS"; emp[2] = "JAVASCRIPT"; for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br>"); } </script> </body> </html>
OUTPUT:
HTML
CSS
JAVASCRIPT
JavaScript array constructor (new keyword):
Create an instance of an array by passing arguments in the constructor so that we don’t have to provide value explicitly.
Example:
<html> <body> <script> var emp=new Array("hello","welcome","I2tutorials"); for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br>"); } </script> </body> </html>
OUTPUT:
hello
welcome
I2tutorials