同原生 JS 的 forEach 方法一致,原生 JS 的map 方法也不能遍历伪数组,但是 JQuery 的 map 方法可以实现遍历伪数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>静态方法-map</title> <script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"> </script> <script> $(function () { var arr = [1, 3, 5, 7, 9]; console.log(arr); $div = $("div"); console.log($div);
arr.map(function (value, index, array) { console.log(index, value) });
$.map(arr, function (value, index) { console.log(index, value) });
$.map($div, function (value, index) { console.log(value, index); }) }) </script> </head> <body> <div>div1</div> <div>div2</div> <div>div3</div> </body> </html>
|
既然jQuery
的each
方法和map
方法都是遍历(伪)数组,那么这两者有什么区别呢?
还是以此为例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>静态方法-map</title> <script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"> </script> <script> $(function () { $div = $("div");
var map = $.map($div, function (value, index) { console.log(value, index); });
var each = $.each($div, function (index, value) { console.log(value, index); });
console.log(map); console.log(each); }) </script> </head> <body> <div>div1</div> <div>div2</div> <div>div3</div> </body> </html>
|