for…in iterates over property names, not values (and did so in an unspecified order up until ES2020*). You shouldn’t use it to iterate over arrays. For them, there’s ES6’s Array.prototype.entries, which now has support across current browser versions:
const myArray = [123, 15, 187, 32];
for (const [i, value] of myArray.entries()) {
console.log(`
{value}`);
}
// 0: 123
// 1: 15
// 2: 187
// 3: 32
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }
Or, for extended compatibility with older browsers, there’s ES5’s forEach method that passes both the value and the index to the function you give it:
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
For iterables in general (where you would use a for…of loop rather than a for…in), iterator helpers are now in the language. You can use Iterator.prototype.forEach to iterate over an entire iterable with an index:
function* fibonacci() {
let a = 0;
let b = 1;
for (;;) {
yield a;
[a, b] = [b, a + b];
}
}
fibonacci().take(10).forEach((x, i) => {
console.log(`F_
{x}`);
});
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }
More generally, Iterator#map can associate the values yielded by an iterator with their indexes:
fibonacci().map((x, i) => [i, x])
Not every iterable (or iterator!) is an Iterator, but you can convert every iterable to an Iterator with Iterator.from.
Without support for iterator helpers, you can use a generator function instead:
function* enumerate(iterable) {
let i = 0;
for (const x of iterable) {
yield [i, x];
i++;
}
}
for (const [i, obj] of enumerate(myArray)) {
console.log(i, obj);
}
If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.
* The order is still unspecified under certain circumstances, including for typed arrays, proxies, and other exotic objects, as well as when properties are added or removed during iteration.
Answer from Ry- on Stack Overflowfor…in iterates over property names, not values (and did so in an unspecified order up until ES2020*). You shouldn’t use it to iterate over arrays. For them, there’s ES6’s Array.prototype.entries, which now has support across current browser versions:
const myArray = [123, 15, 187, 32];
for (const [i, value] of myArray.entries()) {
console.log(`
{value}`);
}
// 0: 123
// 1: 15
// 2: 187
// 3: 32
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }
Or, for extended compatibility with older browsers, there’s ES5’s forEach method that passes both the value and the index to the function you give it:
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
For iterables in general (where you would use a for…of loop rather than a for…in), iterator helpers are now in the language. You can use Iterator.prototype.forEach to iterate over an entire iterable with an index:
function* fibonacci() {
let a = 0;
let b = 1;
for (;;) {
yield a;
[a, b] = [b, a + b];
}
}
fibonacci().take(10).forEach((x, i) => {
console.log(`F_
{x}`);
});
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }
More generally, Iterator#map can associate the values yielded by an iterator with their indexes:
fibonacci().map((x, i) => [i, x])
Not every iterable (or iterator!) is an Iterator, but you can convert every iterable to an Iterator with Iterator.from.
Without support for iterator helpers, you can use a generator function instead:
function* enumerate(iterable) {
let i = 0;
for (const x of iterable) {
yield [i, x];
i++;
}
}
for (const [i, obj] of enumerate(myArray)) {
console.log(i, obj);
}
If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.
* The order is still unspecified under certain circumstances, including for typed arrays, proxies, and other exotic objects, as well as when properties are added or removed during iteration.
In ES6, it is good to use a for... of loop.
You can get index in for... of like this
for (let [index, val] of array.entries()) {
// your code goes here
}
Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
Videos
Use Array.prototype.keys:
for (const index of ["a", "b", "c", "d", "e"].keys()) {
console.log(index);
}
If you want to access both the key and the value, you can use Array.prototype.entries() with destructuring:
for (const [index, value] of ["a", "b", "c", "d", "e"].entries()) {
console.log(index, value);
}
Array#entries returns the index and the value, if you need both:
for (let [index, value] of array.entries()) {
}
As the title states, I was given this prompt
Using a loop, iterate through this array and after console.logging “Mary”, exit from the loop.
The array is
let people = ['Matt', 'Mary', 'Devon', 'Anthony']
I tried this for loop & technically I was able to get the result, but I'm pretty sure it's not the right way.
for (k = 0; k < 4; i++){
if (people.splice(2,4)) {
console.log(people);
break;
} else {
console.log(people[k]);
}
}Could someone please correct me if I'm wrong.
I tried setting the conditional to
k < 1
That way it counts from the 0 index, to the first, which is where Mary is & then
exit
From the loop by using
break;
But that didn't work with my if statement of
if (people) {}That's why I just decided to use the splice method to kind of brute force the result per se.
This is what my original code looked like
for (k = 0; k < 1; i++){
if (people) {
console.log(people[k]);
break;
} else {
console.log(people[k]);
}
}But this way only prints Matt at the beginning of the array.
This is just meant to be an addition to jonas w's solutions.
If you need the key of the current value:
Copyconst object = {a:2, b:4, c:6, d:8};
for (const [index, [key, value]] of Object.entries(Object.entries(object))) {
console.log(`${index}: ${key} = ${value}`);
}
Object.entries(object).forEach(([key, value], index) => {
console.log(`${index}: ${key} = ${value}`);
});
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Of course, you can leave out the key at any time:
Copyconst object = {a:2, b:4, c:6, d:8};
for (const [index, [, value]] of Object.entries(Object.entries(object))) {
console.log(`${index}: ${value}`);
}
Object.entries(object).forEach(([, value], index) => {
console.log(`${index}: ${value}`);
});
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Simply count the index:
Copylet index = 0;
for (let value of object) {
//do something with rest
if (index >= 1) {
// do something with the third and following items
}
index++;
}
Or if you really want to use object destructuring ( i dont know why ) its a bit more complicated:
Copylet entries = Object.entries(object);
for(let [index, [key, value]] of entries.entries()){
//...
}
or:
Copyfor(let [index,value] of Object.values(object).entries()){
//...
}
But i dont know why youre not using a simple forEach?:
CopyObject.values(obj).forEach((value, index)=> /*...*/);