We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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 中对于对象迭代有多种方式,但是各种方式之间都有一些微小的不同
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 为不可枚举的属性
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 无法遍历出不可枚举的属性,但是
for…in
'unenumerable' in obj === true
通过分析测试结果可以得出初步结论
方法 string key Symbol key Prototype 不可枚举 for...in ✅ ❌ ✅ ❌ Object.getOwnPropertyNames ✅ ❌ ❌ ✅ Object.getOwnPropertySymbols ❌ ✅ ❌ ✅ Reflect.ownKeys ✅ ✅ ❌ ✅ Object.keys ✅ ❌ ❌ ❌
通过结论,结合日常使用,进行分析,由于 Symbol 一般来说是用来做内建属性的,不需要被遍历出来,而 prototype 中的属性也类似,一般是不希望被遍历出来的,对于不可枚举的属性也是同样的
Symbol
prototype
所以我认为,最常用的应当是 Object.keys 这一类。它能遍历出来的东西最少,收到的干扰也最少。
Object.keys
#前端
The text was updated successfully, but these errors were encountered:
No branches or pull requests
JavaScript 中对于对象迭代有多种方式,但是各种方式之间都有一些微小的不同
测试分析
以下为我的测试代码
在测试代码中, 进行遍历的对象是这样的,
unenumerable
为不可枚举的属性经代码测试后,发现
另外要说明一点,虽然
for…in
无法遍历出不可枚举的属性,但是结论
通过分析测试结果可以得出初步结论
通过结论,结合日常使用,进行分析,由于
Symbol
一般来说是用来做内建属性的,不需要被遍历出来,而prototype
中的属性也类似,一般是不希望被遍历出来的,对于不可枚举的属性也是同样的所以我认为,最常用的应当是
Object.keys
这一类。它能遍历出来的东西最少,收到的干扰也最少。#前端
The text was updated successfully, but these errors were encountered: