概述
$Each 是一个常见的 JavaScript 库或框架中的方法,用于迭代数组或对象的元素,并生成相应的 HTML 或其他内容。具体用法如下:
使用方法
1、使用数组迭代:
const fruits = ['apple', 'banana', 'orange'];
$.each(fruits, (fruit, index) => {
console.log(fruit, index);
});
输出结果:
apple 0
banana 1
orange 2
在这个例子中,$Each 方法将遍历 fruits 数组的每个元素,并对每个元素执行回调函数。回调函数接收两个参数:当前元素的值和索引。
2、使用对象迭代:
const person = {
name: 'John',
age: 30,
occupation: 'developer'
};
$.each(person, (value, key) => {
console.log(key, value);
});
输出结果:
name John
age 30
occupation developer
在这个例子中,$Each 方法将遍历 person 对象的每个属性,并对每个属性执行回调函数。回调函数接收两个参数:当前属性的值和属性名。
3、例子
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>$each遍历</title>
<script type="text/javascript" src="plugins/jquery3.3.1.min.js"></script>
</head>
<body>
</body>
<script>
$(function () {
var arr = [{
'name': 'tom',
'age': 20
}, {
'name': 'jack',
'age': 18
}];
//遍历数组对象
$.each(arr, function (index, element) { //index = 0, element = {name: "tom", age: 20}
console.log(index, element);
});
//遍历数组
var array = [4, 'tom', true];
$.each(array, function (index, value) { //index = 0, value = 4
console.log(index, value);
});
//遍历对象
var ele = {
'name': 'tom',
'age': 20
};
$.each(ele, function (key, value) { //key = "name", value = "tom"
console.log(key, value);
});
})
</script>
</html>
调试结果:
关注博主:https://blog.csdn.net/sunriver2000