[js] Summary of object traversal methods


1. Commonly used traversal methods for objects

 	for...in
    Object.keys()
    Object.getOwnPropertyNames()
    Object.getOwnPropertySymbols()
    Reflect.ownKeys()

2. Object attribute classification and Symbol attributes

1. Attribute classification of objects

  • Prototype properties
  • The enumerable properties of the object itself
  • non-enumerable properties of the object itself
  • symbol attribute
// 注意: Object.create是利用给定的对象作为原型对象进行创建新的对象
const obj = Object.create({
    
    
    bar: 'bar'// 原型属性
});
obj.foo = 'foo';// 对象的自身可枚举属性
Object.defineProperty(obj, 'name', {
    
    // 对象自身不可枚举的属性
    enumerable: false,
    value: 'kongs'
});
obj[Symbol('age')] = 'age'; // 对象的symbol属性

2. About the expansion of Symbol attributes

The code is as follows (example):

1、let a = Symbol('a'), 创建symbol实例是不能用new创建的
2、具有相同描述的symbol实例是不相等的, Symbpl('b') != Symbol('b')
3、如果想得到同一个描述的相等的两个symbol,可以这样:Symbol.for('c') == Symbol.for('c')

3. Description of object traversal methods

1.for…in loop

  • This method can obtain the enumerable properties of the object itself + the enumerable properties on the prototype chain, but does not include the symbol property.
// 3.1
for(let key in obj) {
    
    
   console.log(key)
};
// 结果会输出: bar foo



// 3.2 如果想过滤掉原型上的属性可以这样:
for(let key in obj) {
    
    
   if (obj.hasOwnProperty(key)) {
    
    
       console.log(key)
   }
};
// 结果会输出:  foo

// 3.3 for..in的输出顺序:
// 对于大于等于0的整数,会按照大小进行排序, 对于小数和负数就会当作字符串处理
// 对于string类型,按照第一的顺序进行输出
// symbol属性将被过滤掉,不会输出

const obj2 = {
    
    
   5: '5',
   a: 'a',
   1: '1',
   c: 'c',
   '-1': '-1',
   '3': '3',
   b: 'b'
}
for(let key in obj2) {
    
    
   console.log(key);
}

// 结果会输出:  1 3 5  a c -1 b

2.Object.keys() method

  • This method obtains the enumerable properties of the object itself
  • Excludes enumerable properties and symbol properties on prototypes
  • es5 new
Object.keys(obj).forEach(key =>  console.log(key)) // 输出: foo

3.Object.getOwnPropertyNames() method

  • This method obtains all properties of the object itself, including non-enumerable properties
  • But does not include prototype attributes and symbol attributes
  • es5 new
Object.getOwnPropertyNames(obj).forEach(i => console.log(i))// 输出: foo name
// 拓展:如何判断属性是否可以枚举?
//方法一:
 Object.getOwnPropertyDescriptor(obj, 'name')
//方法二:
Object.prototype.propertyIsEnumerable.call(obj, ['name'])

4.Object.getOwnPropertySymbols() method

  • This method obtains all symbol attributes of the object itself
  • Excludes symbol attribute on prototype
  • es6 new
Object.getOwnPropertySymbols(obj).forEach(i => console.log(i));// 输出: Symbol(age)

5.Reflect.ownKeys() method

  • This method obtains all properties of the object itself, including non-enumerable and symbol properties.
  • es6 new
Reflect.ownKeys(obj).forEach(i => console.log(i)); // 输出: foo name Symbol(age)

Guess you like

Origin blog.csdn.net/qq_48896417/article/details/126806253