一,先说for in
- for in 用于遍历对象的属性,包括原型链上的可枚举属性
- 遍历数组,(注意遍历结果是数组的索引都为字符串类型)
var arr = [1, 2, 3]
Array.prototype.name = 'xl'
for(let index in arr) {
console.log(typeof index, index+':'+arr[index])
<!--string 0:1-->
<!--string 1:2-->
<!--string 2:3-->
<!--string name:xl-->
}
复制代码
二,Object.keys()
- 遍历结果为对象自身可枚举属性组成的数组
- 不能遍历出原型链上的属性
var arr = [1, 2, 3]
Array.prototype.name = 'xl'
console.log(Object.keys(arr)) //['0', '1', '2']
复制代码
三,for of
- 支持遍历数组,类对象(DOM NodeList对象),字符串
- 不支持遍历普通对象,也不能遍历出原型链上的属性
- 遍历的结果为数组元素的值
var obj = {
name: 'xl',
age: 29
}
for (let key of obj) {
console.log(key)
}
// obj is not iterable 不支持遍历普通对象
复制代码
var arr = [1, 5, 3]
for (let val of arr) {
console.log(val) //1, 5, 3
}
复制代码
补充说明:数组实例的entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)。
for of 搭配实例方法entries(),同时输出数组内容和索引;
let arr3 = ['a', 'b', 'c'];
for (let [index, val] of arr3.entries()) {
console.log(index + ':' + val);//0:a 1:b 2:c
}
复制代码
四,hasOwnProperty()
用于判断自身属性与继承属性 :obj.hasOwnProperty(prop) 返回一个布尔值
var o = new Object();
Object.prototype.name = 'xl';
o.prop = 'xl';
console.log(o.hasOwnProperty('name')) //false
console.log(o.hasOwnProperty('prop')) //true
复制代码