静态方法-each

jQuery 除了拥有与原生 JS 的 forEach 一样的功能之外,还可以遍历伪数组

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
49
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>静态方法-each</title>
<script
src="https://code.jquery.com/jquery-1.12.4.js"
integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU="
crossorigin="anonymous">
</script>
<script>
$(function () {
const arr = [1, 3, 5, 7, 9];
/*
* 原生 JS 遍历数组
* 注意:
* 1.原生的 forEach 方法只能遍历数组,不能遍历伪数组
* 2.传入参数的顺序为先 value ,再 index
*/
arr.forEach(function (value, index) {
console.log(index, value)
});
/*
* 利用 jQuery 的 each 方法遍历数组
* 注意:
* 传入的参数为先 index ,再 value
* 可以遍历伪数组
*/
$.each(arr, function (index, value) {
console.log(index, value);
});

// 遍历伪数组
var $div = $("div");
console.log($div);
$.each($div, function (index, value) {
console.log(index, value);
})
})
</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

×