for in,Object.keys,for of 的区别

1、for in

  • 遍历对象及其原型链上可枚举的属性;
  • 如果用于遍历数组,处理遍历其元素外,还会遍历开发者对数组对象自定义的可枚举属性及其原型链上的可枚举属性;
  • 遍历对象返回的属性名和遍历数组返回的索引都是 string 类型;
  • 某些情况下,可能按随机顺序遍历数组元素;

举个栗子:

Array.prototype.getLength = function() {
    return this.length;
};
var arr = ['a', 'b', 'c'];
arr.name = 'June';
Object.defineProperty(arr, 'age', {
    enumerable: true,
    value: 17,
    writable: true,
    configurable: true
});
for(var i in arr) {
    console.log(i); // 0,1,2,name,age,getLength
}
复制代码

综上考虑,不推荐在数组中使用 for in 遍历

2、Object.keys

  • 返回对象自身可枚举属性组成的数组
  • 不会遍历对象原型链上的属性以及 Symbol 属性
  • 对数组的遍历顺序和 for in 一致

再来个栗子:

function Person() {
    this.name = 'June';
}
Person.prototype.getName = function() {
    return this.name;
}
var person = new Person();
Object.defineProperty(person, 'age', {
    enumerable: true,
    value: 17,
    writable: true,
    configurable: true
});
console.log(Object.keys(person));   // ['name', 'age']
复制代码

3、for of

  • es6 中添加的循环遍历语法;
  • 支持遍历数组,类数组对象(DOM NodeList),字符串,Map 对象,Set 对象;
  • 不支持遍历普通对象;
  • 遍历后输出的结果为数组元素的值;
  • 可搭配实例方法 entries(),同时输出数组的内容和索引;

多举几个栗子:

// 1. 不会遍历到对象属性及其原型属性
Array.prototype.getLength = function() {
    return this.length;
};
var arr = ['a', 'b', 'c'];
arr.name = 'June';
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 配合
var person = {
    name: 'June',
    age: 17,
    city: 'guangzhou'
}
for(var key of Object.keys(person)) {
    console.log(person[key]); // June, 17, guangzhou
}

// 3. 配合 entries 输出数组索引和值/对象的键值
var arr = ['a', 'b', 'c'];
for(let [index, value] of Object.entries(arr)) {
    console.log(index, ':', value);
    // 0:a, 1:b, 2:c
}
var obj = {name: 'June', age: 17, city: 'guangzhou'};
for(let [key, value] of Object.entries(obj)) {
    console.log(key, ':', value);
    // name:June,age:17,city:guangzhou
}

复制代码

Object.entries(obj): 如果参数的数据结构具有键和值,则返回一个二元数组,数组的每个元素为参数的[key,value]数组; 此方法签名如下:

Object.entries(value: any) : Array<[string: any]>
复制代码

栗子:

// Symbol 属性会被忽略
Object.entries({ [Symbol()]: 123, name: 'June', age: 17});
// [['name','June'], ['age', 17]]
复制代码

转载于:https://juejin.im/post/5b2617e5f265da5954425022

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值