How to declare an array in javascript?

JavaScript arrays are used to store multiple values in a single variable. An array is a special variable, which can hold more than one value at a time.

Method 1:

var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array
var name = cars[0];//Saab
This statement modifies the first element in cars:
cars[0] = "Opel";

'Saab' is replaced by 'Opel'.

Method 2:

var cars = ["Saab", "Volvo", "BMW"];

Method 3:

var person = [];

var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;         // person.length will return 3
var y = person[0];             // person[0] will return "John"

Method 4:

var person = {firstName:"John", lastName:"Doe", age:46};

In this example, person.firstName returns 'John'

No comments:

Post a Comment