Javascript Data Structure Tutorial - Javascript Array Element








Data can be assigned to array elements using the [] operator in an assignment statement.

The following loop assigns the values 1 through 100 to an array:

var nums = []; 
for (var i = 0; i < 100; ++i) { 
    nums[i] = i+1; 
} 

The code above used a for loop which iterates from 0 to 99.

Array elements can be accessed using the [] operator. For example:

var numbers = [1,2,3,4,5]; 
var sum = numbers[0] + numbers[1] + numbers[2] + numbers[3] + numbers[4]; 
console.log(sum); 

The code above generates the following result.

Example

Accessing all the elements of an array sequentially is easier using a for loop:

var numbers = [1,2,3,5,8,13,21]; 
var sum = 0; 
for (var i = 0; i < numbers.length; ++i) { 
    sum += numbers[i]; 
} 
console.log(sum);  

The code above generates the following result.

for loop is controlled using the length property rather than an integer literal. In this way we can make sure that we will iterate all elements from an array.





Creating Arrays from Strings

We can create Arrays by calling the split() function on a string. For example, we can split all words in a string by space letter.

This function breaks up a string with a delimiter, such as a space, and creates an array consisting of the individual parts of the string.

The following code demonstrates how the split() function works on a simple string:

var sentence = "This is a test"; 
var words = sentence.split(" "); 
for (var i = 0; i < words.length; ++i) { 
    console.log("word " + i + ": " + words[i]); 
}