How to traverse js array? This article will introduce to you how js traverses one-dimensional arrays, and let you know the three methods of one-dimensional array traversal in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
One-dimensional array traversal in js can basically be implemented using some methods such as for, forin, foreach, forof, map, etc. Below we will focus on the three types of array traversal: for, forin, and foreach. How the method is implemented is explained through a simple code example.
Using for loop in jsTraverse the array
##
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="text/javascript"> var arr = [11, 22, 33, 55]; //普通的循环遍历方式 function first() { for(var i = 0; i < arr.length; i++) { console.log("arr[" + i + "]:" + arr[i]); } } </script> <input type="button" value="for循环遍历" name="aa" onclick="first();" /><br/> </body> </html>
Using for in loop in jsTraverse the array
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="text/javascript"> var arr = [11, 22, 33, 55]; //for ..in循环遍历方式 function second() { for(var index in arr) { console.log("arr[" + index + "]:" + arr[index]); } } </script> <input type="button" value="for...in遍历" name="aa" onclick="second();" /><br/> </body> </html>
Using foreach loop in jsTraverse the array
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="text/javascript"> var arr = [11, 22, 33, 55]; //很鸡肋的遍历方式---forEach function third() { arr.forEach(function(ele, index) { console.log("arr[" + index + "]:" + ele); }); } </script> <input type="button" value="forEach循环遍历" name="aa" onclick="third();" /><br/> </body> </html>
JavaScript Video Tutorial, jQuery Video Tutorial, bootstrap Tutorial!
The above is the detailed content of How to perform array traversal in js? 3 methods of one-dimensional array traversal in js (detailed explanation with pictures and texts). For more information, please follow other related articles on the PHP Chinese website!