Array.prototype.keysintermediateconst arr = ['red', 'green', 'blue']
for (const i of arr.keys()) {
console.log(i) // 0, 1, 2
}Use keys() with for-of to iterate over only the indices of an array.
Because keys() returns an iterator, you can consume it directly inside a forβ¦of loop without converting it first. This is useful when you want to build up a result array manually.
Challenge: Implement keysToArray(arr) using a forβ¦of loop over arr.keys() to collect all indices.
keysToArray(['x', 'y', 'z']) // β [0, 1, 2]
keysToArray([]) // β []