Closed
Bug 1285453
Opened 9 years ago
Closed 9 years ago
for-of of Objects is not described
Categories
(Developer Documentation Graveyard :: JavaScript, defect, P5)
Tracking
(Not tracked)
RESOLVED
FIXED
People
(Reporter: ron, Unassigned)
References
()
Details
:: Developer Documentation Request
Request Type: New Documentation
Gecko Version: unspecified
Technical Contact:
:: Details
All kinds of specific classes (iterators) and arrays are shown in examples. But how for-of behaves on plain objects is not demonstrated. Is there a way to get both key and value in the iteration? In other words: how does Object iterate?
Comment 1•9 years ago
|
||
for-of iterates over "iterable object" [1], so plain Object without iterable protocol is not iterable with for-of (it will just throw an exception)
Object.entries [2][3] will help you iterating over plain object's key-value pairs, but it's still experimental and not-available on some browsers.
maybe we could add an example with minimal iterable object there.
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable
[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
[3] https://tc39.github.io/ecma262/#sec-object.entries
Comment 2•9 years ago
|
||
Added an example with iterable protocol.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Iterating_over_other_iterable_objects
does it make sense? or do you need any other example?
Flags: needinfo?(ron)
Great, thanks for the quick clarification and doc improvement. I was under the false assumption that normal Object instances had a default iterator, allowing one to simply for-of on { a: 1, b: 2 }. I wonder why that isn't possible in the first place though, it would be a very nice default.
Comment 4•9 years ago
|
||
adding default iterator will break existing web apps, as it could be observable via property access in other places.
When Object.entries becomes non-draft spec (maybe next year?) and available on all browsers, you can iterator with the following code:
for (let [key, value] of Object.entries(obj)) ...
Status: UNCONFIRMED → RESOLVED
Closed: 9 years ago
Flags: needinfo?(ron)
Resolution: --- → FIXED
You need to log in
before you can comment on or make changes to this bug.
Description
•