经实验证实js中forEach只能遍历数组,不能遍历类数组
jQuery中each方法可以遍历数组和类数组
forEach方法
无法跳出循环,只能通过抛出异常暴力跳出循环。
<body>
<div>
</div>
<script>
var odiv = document.getElementsByTagName('div');//odiv是类数组
var arr = [1,2,3,4];
console.log(odiv);
console.log(arr);
arr.forEach(function(ele,index){
console.log(ele);
})
odiv.forEach(function(ele,index){
console.log(ele);
})
</script>
</body>
let arr = [
{a: 1},
{b: 2},
{c: 3},
];
arr.forEach((item, index, arr)=>{
console.log(item, index, arr);
});
运行结果:
jQuery中each方法:
<body>
<div>
</div>
<script src="./jquery.js"></script>
<script>
var arr = [1,2,3,4];
$(arr).each(function(index,ele){
console.log(ele);
})
$('div').each(function(index,ele){
console.log(ele);
})
</script>
</body>
运行结果:
其他遍历数组的方法
for 循环
可以跳出循环
let arr = [1,2,3,4,5];
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
};
//break 退出本层循环
for (let i = 0; i < arr.length; ++i) {
if(arr[i] > 3) {
console.log(arr[i]);
break;
}
}
for...in...
for…in 循环:使用 for…in 循环可以遍历数组中的所有元素,包括数组原型链上的属性和方法,因此通常不推荐使用。
Array.prototype.num = 9;
let arr = [1, 2, 3, 4, 5];
for (let index in arr) {
console.log(arr[index]);
}
// 此时9也会被遍历出来
for...of...,
使用 for…of 循环可以遍历数组中的所有元素,但不包括数组原型链上的属性和方法。
rray.prototype.num = 9;
let arr = [1, 2, 3, 4, 5];
for (let item of arr) {
console.log(item);
}
// 9不会被遍历出来
迭代器 entries()
很少用到
let arr = [1, 2, 3, 4, 5];
for (let [index, value] of arr.entries()) {
console.log(`Index: ${index}, Value: ${value}`);
}
遍历对象
for...in...
使用 for...in 循环可以遍历对象自身以及原型链上的可枚举属性。
let obj = {
a: 1,
b: 2,
};
Object.prototype.c = 3;
for (let key in obj) {
console.log(key, obj[key]);
}
// 结果
// a 1
// b 2
// c 3
// 定义一个父对象
var parent = {
parentProp: 'parent...'
};
// 定义一个子对象,它继承自父对象
var child = Object.create(parent);
child.childProp = 'child...';
// 使用 for...in 循环遍历子对象的所有属性,包括原型链上的属性
for (var prop in child) {
if (child.hasOwnProperty(prop)) {
console.log('child has own property:', prop);
} else {
console.log('child inherits property:', prop);
}
}
// child has own property: childProp
// child inherits property: parentProp
// child inherits property: c
Object.keys()
使用 Object.keys() 方法可以获取对象的所有可枚举属性的键名组成的数组。 Object.values()
Object.values()
方法可以获取对象的所有可枚举属性的值组成的数组。
Object.entries()
使用 Object.entries() 方法可以获取对象的所有可枚举属性的键值对组成的数组。