How to use array index to get and set value in Javascript

Description

To get and set array values, use square brackets and the zero-based numeric index.

Example


var colors = ["red", "blue", "green"];      
console.log(colors[0]);                     
colors[2] = "new black";                        //change the third item
colors[3] = "new brown";                        //add a fourth item
console.log(colors.toString());//w  w w.j  a va 2 s .  c o m


var myArray = new Array();
myArray[0] = 100;
myArray[1] = "Adam";
myArray[2] = true;
console.log(myArray.toString());

The code above generates the following result.

Note

If the index is less than the number of items in the array, then it will return the value in the getter and replace the value in the setter.

If a value is set to an index that is beyond the end of the array, the array is expanded.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions