Monday, 11 January 2016

JavaScript - Best way to traverse an array in JavaScript


There are several ways to traverse through an array in JavaScript. The idea is to access the array elements by an index variable and keep incrementing it until the array length.

But what if some array elements have undefined values , what if the number of array elements having valid values are less than the total length of the array. Such cases are handled by explicit checks on element values and array length.

One of the better way is to use the for .. in statement. It will skip all the undefined values and you don't have to keep track of the valid index values or the array length. Below is the code,


<?xml version="1.0" encoding="utf-8" ?>
<html>
<head>
<title> display all heading types page </title>
<script type="text/javascript">
<!--
var arr1 = [5,,7,8];
for ( var element in arr1)
{
document.writeln(arr1[element]);
}


// -->
</script>
</head>

</html> 

Variable element will have only the valid index values ie the indexes at which array elements have definite values. Thus index value 1 will be skipped as there is no value at arr1[1]. The above code will print 5 7 8 . 


I hope it helps :)

No comments:

Post a Comment