- forEach:更多用来循环数组的,但是不能通过return、break终止循环
var arr = [11, 22, 33, 24]
arr.forEach(element => {
if (element == 22) return
console.log(element) // 11 33 24
})
- for of:通常用来遍历数组的,循环得到的是value
var arr = [11, 22, 33, 24]
for (const key of arr) {
console.log(key) // 11 22 33 24
}
- for in:通常用来遍历对象的,循环得到的是key,会遍历原型链上可枚举的属性
( Object.hasOwnProperty()方法判断某个属性是否是该对象自身的属性,而不是原型链上的 )
// 遍历对象
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o in obj) {
console.log(o) //遍历的实际上是对象的属性名称 a,b,c,d
console.log(obj[o]) //这个才是属性对应的值1,2,3,4
}
// =====================================================================
1、Object.hasOwnProperty.call(obj, key)
var obj = {
name: 'hehe',
age: 12
}
Object.prototype.gender = '女'
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
// 判断是不是自身上的属性,不包含原型链上的;返回布尔值
const element = obj[key]
console.log(element) // hehe 12
}
}
// =====================================================================
2、Object.hasOwnProperty(key):
Object.prototype.gender = '女'
var person = {
name: 'tebu',
age: 12
}
for (var key in person) {
if (person.hasOwnProperty(key)) {
console.log(key, person[key])
}
}
// name tebu
// age 12