for in一般用于遍历对象的属性;
作用于数组的for in除了会遍历数组元素外,还会遍历自定义可枚举的属性,以及原型链上可枚举的属性;
作用于数组的for in的遍历结果是数组的索引,且都为字符串型,不能用于运算;
某些情况下,可能按照随机顺序遍历数组元素;
Array.prototype.sayLength = function(){
console.log(this.length);
}
let arr = ['a','b','c','d'];
arr.name = '数组';
Object.defineProperties(arr,{
type:{
value:true,
writable:true,
enumerable:true
}
});
for(let i in arr){
console.log(i);//0,1,2,3,name,type,sayLength
}
Object.keys()
遍历结果为由对象自身可枚举属性组成的数组,数组中的属性名排列顺序与使用for in循环遍历该对象时返回的顺序一致;
与for in区别在于不能遍历出原型链上的属性;
Array.prototype.sayLength = function(){
console.log(this.length);
}
let arr = ['a','b','c','d'];
arr.name = '数组';
Object.defineProperties(arr,{
type:{
value:true,
writable:true,
enumerable:true
}
});
var keys = Object.keys(arr);
console.log(keys);//["0", "1", "2", "3", "name", "type"]