是啊,平常用each方法,遍历最多的估计就是HTML元素,然而万万没有想到的是each还可以遍历数组,还是对象啊,因为js的原生其实都有对应的方法,所以就很少用jQuery自带的方法了,毕竟要用jQuery还需要引入这个js文件,还是挺麻烦的。
不过,既然已经知道了jQuery中的each可以用来遍历数组/对象的话,那么都统一讲下吧,这里我就直接拿例子来讲吧。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jQuery使用each方法遍历HTML元素/数组/对象</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
//遍历HTML元素
$("ul > li").each(function (index, element) {
console.log(index + "——" + element);
}); //输出结果为:0——li元素 1——li元素 2——li元素
//遍历数组
const arr = [1, 2, 3];
$.each(arr, function (index, value) {
console.log(index + "——" + value);
}); //输出结果为:0——1 1——2 2——3
//遍历对象
const obj = { name: "野人" };
$.each(obj, function (index, value) {
console.log(index + "——" + value);
}); //输出结果为:name——野人
</script>
</body>
</html>