js腳本中 forEach()循環. each()循環及普通for循環


  1. js中普通for循環
 1  var array = [5, 4, 3, 2, 1];
 2         var $array = $(array);
 3         $("body>ul").append("js中的普通for循環");
 4         for (var i = 0; i < array.length; i++) {
 5             $("body>ul").append("<p>" + array[i] + "&nbsp;&nbsp;&nbsp;&nbsp;" + i + "</p>") ;
 6         }
 7 js中的普通for循環
 8 5    0
 9 
10 4    1
11 
12 3    2
13 
14 2    3
15 
16 1    4

  2.js的forEach()循環

 1 $("body>ul").append("js中的forEach()循環");
 2         array.forEach(function (element, index) {
 3             $("body>ul").append("<p>" + element + "&nbsp;&nbsp;&nbsp;&nbsp;" + index + "</p>")  ;
 4         });
 5 ----------------------------------------
 6 js中的forEach()循環
 7 5    0
 8 
 9 4    1
10 
11 3    2
12 
13 2    3
14 
15 1    4

  3.jQuery中的each()循環

  • //這是轉換成jQuery對象的方法
 $array.each(function (i) {
            $("body>ul").append("<p>" + this + "&nbsp;&nbsp;&nbsp;&nbsp;" + (i++) + "</p>");
        }) ;
----------------------------------
jQuery中的forEach()循環
5    0

4    1

3    2

2    3

1    4
  • 沒有轉換成jQuery對象的使用方法
  $.each(array,function (index,element) {
            $("body>ul").append("<p>" + element + "&nbsp;&nbsp;&nbsp;&nbsp;" + index + "</p>");
        })
--------------------------------------------------
5    0

4    1

3    2

2    3

1    4
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <script src="js/jquery-1.12.4.min.js"></script>
 8 <script>
 9     $(document).ready(function () {
10         var array = [5, 4, 3, 2, 1];
11         var $array = $(array);
12         $("body>ul").append("js中的普通for循環");
13         for (var i = 0; i < array.length; i++) {
14             $("body>ul").append("<p>" + array[i] + "&nbsp;&nbsp;&nbsp;&nbsp;" + i + "</p>") ;
15         }
16         $("body>ul").append("js中的forEach()循環");
17         array.forEach(function (element, index) {
18             $("body>ul").append("<p>" + element + "&nbsp;&nbsp;&nbsp;&nbsp;" + index + "</p>")  ;
19         });
20 
21         $("body>ul").append("jQuery中的forEach()循環");
22             //這是轉換成jQuery對象的方法
23         $array.each(function (i) {
24             $("body>ul").append("<p>" + this + "&nbsp;&nbsp;&nbsp;&nbsp;" + (i++) + "</p>");
25         }) ;
26         $("body>ul").append("-----------------");
27             //不轉換成jQuery對象的方法
28         $.each(array,function (index,element) {
29             $("body>ul").append("<p>" + element + "&nbsp;&nbsp;&nbsp;&nbsp;" + index + "</p>");
30         })
31     })  ;
32 </script>
33 <body>
34 <ul></ul>
35 </body>
36 </html>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM