js数组的4种遍历方式

 1 <!DOCTYPE html>  
 2 <html>  
 3 <head>  
 4     <meta charset="utf-8"/>  
 5     <title>数组的遍历方式</title>  
 6     <script type="text/javascript">  
 7         var arr = [11, 22, 33, 55];
 8         //普通的循环遍历方式  
 9         function first() {
10 
11             for (var i = 0; i < arr.length; i++) {
12                 console.log("第一种遍历方式\t" + arr[i]);
13             }
14             console.log("111111111111111111111111111111");
15 
16 
17         }
18         //2、for ..in 遍历方式  
19         function second() {
20             // for in 遍历需要两个形参 ,index表示数组的下标(可以自定义),arr表示要遍历的数组  
21             for (var index in arr) {
22                 console.log("第二种遍历方式\t" + arr[index]);
23 
24             }
25             console.log("222222222222222222222222222222");
26         }
27 
28         //3,很鸡肋的遍历方式  
29         function third() {
30             //第一个参数为数组的元素,第二个元素为数组的下标  
31             arr.forEach(function (ele, index) {
32                 console.log("第三种遍历方式\t" + arr[index] + "-----" + ele);
33             });
34             console.log("333333333333333333333333333333");
35 
36         }
37         //4,for-of遍历方式  
38         function forth() {
39             //第一个变量ele代表数组的元素(可以自定义) arr为数组(数据源)  
40             for (var ele of arr) {
41                 console.log("第四种遍历方式\t" + ele);
42             }
43             console.log("444444444444444444444444444444");
44         }
45     </script>  
46 </head>  
47 <body>  
48     <input type="button" value="第一种遍历方式" name="aa" onclick="first();"/><br/>  
49     <input type="button" value="第二种遍历方式" name="aa" onclick="second();"/><br/>  
50     <input type="button" value="第三种遍历方式" name="aa" onclick="third();"/><br/>  
51     <input type="button" value="第四种遍历方式" name="aa" onclick="forth();"/><br/>  
52 </body>  
53 </html>  

 

posted @ 2018-03-26 23:48  Z.ain  阅读(178)  评论(0编辑  收藏  举报