静态方法-map

同原生 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);

/*
* 利用原生 JS 的 map 方法遍历真数组
* 注意:
* 与原生 JS 的forEach 一样不能遍历伪数组
*/
arr.map(function (value, index, array) {
console.log(index, value)
});

/*
* jQuery 中的 map 方法遍历真数组
* 注意:
* jQuery 的 map 方法可以遍历伪数组
*/
$.map(arr, function (value, index) {
console.log(index, value)
});

//jQuery 的 map 方法遍历伪数组
$.map($div, function (value, index) {
console.log(value, index);
})
})
</script>
</head>
<body>
<div>div1</div>
<div>div2</div>
<div>div3</div>
</body>
</html>

既然jQueryeach方法和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");
/*
* 问:each 方法和 map 方法的区别?
* 答:
* 区别一:
* map 方法返回的为一个空的数组; each 方法返回的是遍历的数组(遍历谁,返回谁)
*
* 区别二:
* map 方法中可以添加 return 语句,可实现一些复杂的操作,而 each 则不支持返回值(即使添加了 return 语句,返回值仍然为遍历的数组)
*
* 区别三:
* 回调函数中传入的参数顺序不同
* */

//jQuery 的 map 方法遍历伪数组
var map = $.map($div, function (value, index) {
console.log(value, index);
});

//jQuery 的 each 方法遍历伪数组
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>

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×