舉個栗子: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 遍歷數組
再來個栗子: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']
複製代碼
多舉幾個栗子:數據結構
// 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]]
複製代碼