-
for-in是js中最常见的迭代语句,常常用来枚举对象的属性。某些情况下,可能按照随机顺序便利数组元素。
-
Object构造器有一个实例属性keys,则可以返回以对象的属性为元素的数组。数组中属性名的顺序跟使用for-in遍历返回的顺序是一样的。
-
for-in 循环会枚举对象原型链上的可枚举属性,而Object.keys不会
for in
- 遍历对象及其原型链上的可枚举的属性
- 如果用于遍历数组,除了遍历其元素外,还会遍历开发者对数组对象自定义的可枚举属性及其原型链上的可枚举属性
- 遍历对象返回属性名和遍历数组返回的索引都是string类型
- 某些情况下,可能按随机顺序遍历数组元素
Array.prototype.getLength=function(){
return this.length;
}
var arr=['a','b','c'];
arr.name='jj';
Object.defineProperty(arr,'age',{
enumerable:true,
value:5,
writable:true,
configurable:true
});
for(var i in arr){
console.log(i);
}
不推荐在数组中使用for in 遍历
Object.keys
- 返回对象自身可枚举属性组成的数组
- 不会遍历对象原型链上的属性以及Symbol属性
- 对数组的遍历顺序和for in 一致
function Company(){
this.name='jj';
}
Company.prototype.getName=function(){
return this.name;
}
const jj = new Company();
Object.defineProperty(jj,'age',{
enumerable:true,
value:5,
writable:true,
configurable:true
});
Object.defineProperty(jj,'address',{
enumerable:false,
value:'北京',
writable:true,
configurable:true
});
console.log(Object.keys(jj));
for of
- es6 中添加的循环遍历语法
- 支持遍历数组,类数组对象(DOM NodeList),字符串,Map对象,set对象;
- 不支持遍历普通对象
- 遍历后输出的结果为数组元素的值
- 可搭配实例方法entries(),同时输出数组的内容和索引;
//1. 不会遍历到对象属性及其原型属性
Array.prototype.getLength=function(){
return this.length;
}
const arr=['a','b','c'];
arr.name='jj';
Object.defineProperty(arr,'age',{
enumerable:true,
value:17,
writable:true,
configurable:true
});
for(let i of arr){
console.log(i); // a ,b ,c
};
// 2.如果要遍历对象,可与Object.keys配合
const company={
name:'jj',
age:5,
city:'beijing'
}
for(let key of Object.keys(company)){
console.log(company[key]); // jj ,5 beijing
}
//3. 配合entries输出数组索引和值/对象的键值
const arr=['a','b','c'];
for(let [index,value] of Object.entries(arr)){
console.log(index,':',value);
// 0:a,1:b,2:c
const obj={name:'jj',age:5,city:'beijing'};
for(let [key,value] of Object.entries(obj)){
console.log(key,':',value);
// name:jj,age:5,city:beijing
}
}
Object.entries
Object.entries(obj) :如果参数的数据结构具有键和值,则返回一个二元数组,数组的每个元素为参数的[key,value]数组;
// Symbol 属性会被忽略
Object.entries({[Symbol()]:1,name:'jj',age:5})
本文探讨了JavaScript中的for-in循环和Object.keys()方法的区别。for-in循环不仅遍历对象自身的可枚举属性,还遍历原型链上的属性,而Object.keys()则仅返回对象自身的可枚举属性,不包括原型链。此外,for-in在遍历数组时可能按随机顺序,并不推荐使用。相比之下,ES6的for-of循环和Object.entries()提供了更现代且明确的遍历方式。
3776

被折叠的 条评论
为什么被折叠?



