《你不知道的JavaScript(上卷)》笔记:遍历对象

  • Object.keys 返回一个所有元素为字符串的数组,其元素来自于从给定的object上面可直接枚举的属性。这些属性的顺序与手动遍历该对象属性时的一致。
// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// getFoo is a property which isn't enumerable
var myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  } 
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']
Object.keys("foo");
// TypeError: "foo" is not an object (ES5 code)

Object.keys("foo");
// ["0", "1", "2"]                   (ES2015 code)
  • 遍历数组
var myArray = [1, 2, 3];
for(var i = 0; i < myArray.length; i++) {
    console.log(myArray[i]);
}
// 1 2 3
var myArray = [1, 2, 3];
for(var v of myArray) {
    console.log( v );
}
// 1
// 2
// 3
var myArray = [1, 2, 3];
var it = myArray[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

// { value: 1, done: false }
// { value: 2, done: false }
// { value: 3, done: false }
// { value: undefined, done: true }
  • 对象可枚举
var myObject = {
    a:2
}
console.log("a" in myObject) // true
console.log("b" in myObject) // false
console.log( myObject.hasOwnProperty( "a" ) ) // true
console.log( myObject.hasOwnProperty( "b" ) ) // false
  • 普通的对象没有内置的@@iterator,所以无法自完成for…of遍历。
var myObject = {
    a: 2,
    b: 3
}

Object.defineProperty( myObject, Symbol.iterator, {
    enumerable: false,
    writable: false,
    configurable: true,
    value: function() {
        var o = this;
        var idx = 0;
        var ks = Object.keys( o );
        return {
            next: function() {
                return {
                    value: o[ks[idx++]],
                    done: (idx > ks.length)
                }
            }
        }
    }
} );

var it = myObject[Symbol.iterator]();
console.log( it.next() );
console.log( it.next() );
console.log( it.next() );

// { value: 2, done: false }
// { value: 3, done: false }
// { value: undefined, done: true }

for(var v of myObject) {
    console.log( v );
}

// 2
// 3

猜你喜欢

转载自blog.csdn.net/wuweitiandian/article/details/79546709