Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: iterate over the elements of array

In this post, I am going to explain how to iterate over the elements of Array and explain the drawbacks in every approach.

Let me start with basic approach.

var arr1 = [2, 3, 5, 7];
                          
for(var i=0; i
         document.write(arr1[i] + "
");
}

traversal.html





Array Traversal



"text/javascript">
var arr1 = [2, 3, 5, 7];

for (var i = 0; i arr1.length; i++) {
document.write(arr1[i] + "
"
);
}





What if your array is sparse. If your array is sparse and you use the above approach, you will get lot of undefined values.

traversal.html





Array Traversal



"text/javascript">
var arr1 = [2, 3, 5, 7];
arr1[10] = 1234;

for (var i = 0; i arr1.length; i++) {
document.write(arr1[i] + "
"
);
}





Open above page in browser, you will get following text.

2
3
5
7
undefined
undefined
undefined
undefined
undefined
undefined
1234

One way to resolve this problem is escape all the undefined values.

for(var i=0; i
         if(!arr1[i])
                  continue;
         document.write(arr1[i] + "
");
}


traversal.html





Array Traversal



"text/javascript">
var arr1 = [2, 3, 5, 7];
arr1[10] = 1234;

for (var i = 0; i arr1.length; i++) {
if (!arr1[i])
continue;
document.write(arr1[i] + "
"
);
}





Open above page in browser, you can able to see following text.

2
3
5
7
1234

One problem with above program is, it escapes null values also. If you are specific about escaping only undefined values, you need to update logic like below.


traversal.html





Array Traversal



"text/javascript">
var arr1 = [2, null, 5, 7, null];
arr1[10] = 1234;

for (var i = 0; i arr1.length; i++) {
if (arr1[i] === undefined)
continue;
document.write(arr1[i] + "
"
);
}





Open above page in browser, you can able to see following text.

2
null
5
7
null
1234

Can I use fo-in loop to traverse array?
One problem with for-in loop is it traverse inherited properties also. If you want to traverse and skip inherited properties update your logic like below.

for(var i in arr1){
         if (!arr1.hasOwnProperty(i))
                  continue;
         document.write(arr1[i] + "
");

}



Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: iterate over the elements of array

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×