Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 中 Object 的迭代 #3

Open
SuperTapir opened this issue Apr 5, 2020 · 0 comments
Open

JavaScript 中 Object 的迭代 #3

SuperTapir opened this issue Apr 5, 2020 · 0 comments

Comments

@SuperTapir
Copy link
Owner

JavaScript 中对于对象迭代有多种方式,但是各种方式之间都有一些微小的不同

  • for...in
  • Object.getOwnPropertyNames
  • Object.getOwnPropertySymbols
  • Reflect.ownKeys
  • Object.keys, Object.values, Object.entries

for…of 不适用于 Object

测试分析

以下为我的测试代码

function Foo() {
  this.normal = true;
  this[Symbol('symbol')] = true;
}

Foo.prototype.protoFlag = true;

let obj = new Foo();
Object.defineProperty(obj, 'unenumerable', {
  enumerable: false,
});

let forInArr = [];
for (let key in obj) {
  forInArr.push(key);
}

console.log('for...in', forInArr);
console.log('Object.getOwnPropertyNames', Object.getOwnPropertyNames(obj));
console.log('Object.getOwnPropertySymbols', Object.getOwnPropertySymbols(obj));
console.log('Reflect.ownKeys', Reflect.ownKeys(obj));
console.log('Object.keys', Object.keys(obj));

在测试代码中, 进行遍历的对象是这样的,unenumerable 为不可枚举的属性

{normal: true, unenumerable: undefined, Symbol(symbol): true}

经代码测试后,发现

for...in                      ["normal", "protoFlag"]
Object.getOwnPropertyNames    ["normal", "unenumerable"]
Object.getOwnPropertySymbols  [Symbol(symbol)]
Reflect.ownKeys               ["normal", "unenumerable", Symbol(symbol)]
Object.keys                   ["normal"]

另外要说明一点,虽然 for…in 无法遍历出不可枚举的属性,但是

'unenumerable' in obj === true

结论

通过分析测试结果可以得出初步结论

方法                          string key  Symbol key  Prototype 不可枚举

for...in                          ✅          ❌        ✅       ❌ 
Object.getOwnPropertyNames        ✅          ❌        ❌       ✅ 
Object.getOwnPropertySymbols      ❌          ✅        ❌       ✅ 
Reflect.ownKeys                   ✅          ✅        ❌       ✅ 
Object.keys                       ✅          ❌        ❌       ❌ 

通过结论,结合日常使用,进行分析,由于 Symbol 一般来说是用来做内建属性的,不需要被遍历出来,而 prototype 中的属性也类似,一般是不希望被遍历出来的,对于不可枚举的属性也是同样的

所以我认为,最常用的应当是 Object.keys 这一类。它能遍历出来的东西最少,收到的干扰也最少。

#前端

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant