let arr = [1, 2, 4]
let key = arr.keys();
console.log(key);
for (const k of key) {
console.log(k);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I'm getting confuse when I try to console arr.keys()
it show me undefined
but if there is nothing in it then how we can able to iterate that object that show me 0 1 2
.
CodePudding user response:
You've said
why it show empty object but still able to iterator?
in the title but
I'm getting confuse when I try to console
arr.keys()
it show meundefined
in the question. Those are very different things. It shows you an empty object, not undefined
.
When you look at the iterator from keys
, it doesn't have any properties or methods of its own, it inherits all of them from its prototype. So if the console you're using shows just the object's own properties (like the Stack Snippets console does), it'll look like an empty object.
But it still has state (just not state stored as "own" properties), and it still has the methods that an iterator is expected to have (it inherits them from its prototype). So it fulfills the "interface" of an iterator and works with for-of
.
Here's an example of an iterator that works the same way. This is not how the array iterator is defined (though it's not a million miles off), it's just an example of an iterator with no "own" properties or methods that nonetheless is an iterator:
function* iteratorForKeys(array) {
for (let i = 0; i < array.length; i) {
yield i;
}
}
let keys = iteratorForKeys(["a", "b", "c"]);
console.log(keys); // Empty object if you ignore the prototype
console.log(Object.getOwnPropertyNames(keys).length); // 0
console.log(Object.getOwnPropertySymbols(keys).length); // 0
console.log("Key values:");
for (const key of keys) {
console.log(key);
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
it does not show undefined it shows
Object [Array Iterator] {}, its not undefined but a iterator object when you do arr.keys() it simply makes an iterator of keys [0,1,2], in case of Simple integer or string arrays, index work as keys for example
const array = [34,45,67,89]
console.log(array[2]) // will print 67 as in current array at key 2 position it contains 67 value
if you want to print keys instead of iterator object you can use this code sample
let arr = [1,2,4]
let key = arr.keys();
console.log(key); // will print iterator object i.e Object [Array Iterator] {}
console.log([...key]) //shows [0,1,2], iterator is converted to simple array which you can print