Array traversing and accessing in Data structure with JavaScript
In this article, we will learn about Array traversing and accessing Data structure using JavaScript.
Learn Array traversing and accessing in Data structure
What is Array Traversing?
Array Travesing means to access each element (item) stored in the array so that the data can be checked or used as part of a process.
The array basically contains multiple elements of the same type, We can traverse an array directly by element index, like below:
let arr = [3, 5, 85, 0, 13, 51];
document.write(`Array ${0} = ${arr[0]} <br>`)
document.write(`Array ${1} = ${arr[1]} <br>`)
document.write(`Array ${2} = ${arr[2]} <br>`)
document.write(`Array ${3} = ${arr[3]} <br>`)
document.write(`Array ${4} = ${arr[4]} <br>`)
document.write(`Array ${5} = ${arr[5]} <br>`)
Output:
Array 0 = 3
Array 1 = 5
Array 2 = 85
Array 3 = 0
Array 4 = 13
Array 5 = 51
The above method does not work efficiently when the array is bigger and its also not good pratice to do this, so in this case we can use for loop to raver an array like this:
let arr = [3, 5, 85, 0, 13, 51];
for(let i=0;i<arr.length;i++)
{
document.write(`Array ${i} = ${arr[i]} <br>`)
}
Output:
Array 0 = 3
Array 1 = 5
Array 2 = 85
Array 3 = 0
Array 4 = 13
Array 5 = 51