for in,Object.keys,for of 的區別

一、for in

  • 遍歷對象及其原型鏈上可枚舉的屬性;
  • 若是用於遍歷數組,處理遍歷其元素外,還會遍歷開發者對數組對象自定義的可枚舉屬性及其原型鏈上的可枚舉屬性;
  • 遍歷對象返回的屬性名和遍歷數組返回的索引都是 string 類型;
  • 某些狀況下,可能按隨機順序遍歷數組元素;

舉個栗子:es6

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 遍歷數組

二、Object.keys

  • 返回對象自身可枚舉屬性組成的數組
  • 不會遍歷對象原型鏈上的屬性以及 Symbol 屬性
  • 對數組的遍歷順序和 for in 一致

再來個栗子:bash

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']
複製代碼

三、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]數組; 此方法簽名以下:ui

Object.entries(value: any) : Array<[string: any]>
複製代碼

栗子:this

// Symbol 屬性會被忽略
Object.entries({ [Symbol()]: 123, name: 'June', age: 17});
// [['name','June'], ['age', 17]]
複製代碼
相關文章
相關標籤/搜索