When developing a web application using Node.js, I was turning the list with forEach. I also needed index information in a hurry.
So I wrote the following source code, but my friends pointed out that there was a better way. When I actually tried it, it was very convenient and I felt that it was close to Python's enumerate function, so I will leave it in the article as a way to get the index and value at the same time with the ** for statement **.
ary = ["bar", "foo", "hoge"]
let i = 0
ary.forEach(function( value ) {
console.log(i, value );
i++
});
// 0 bar
// 1 foo
// 2 hoge
A function that gets the index and value of the list specified in the argument.
ary = ["bar", "foo", "hoge"]
for i, item in enumerate(ary):
print(i, item)
# 0 bar
# 1 foo
# 2 hoge
In the forEach function, the first argument is a list and the second argument is an index.
This index is automatically incremented as the number of loops increases, so
You do not have to write i ++
or i + = 1
.
ary = ["bar", "foo", "hoge"]
ary.forEach(function(value, i) {
console.log(i, value);
});
// 0 bar
// 1 foo
// 2 hoge
for in
for in
gets the index of the list.
The index and value are retrieved by the following source code.
ary = ["bar", "foo", "hoge"]
for (i in ary){
console.log(i, ary[i])
}
// 0 bar
// 1 foo
// 2 hoge
On the other hand, for in
may show unexpected behavior as follows, so
It seems that you need to be careful when using it.
var data = [ 'apple', 'orange', 'banana'];
//Added hoge method to array object
Array.prototype.hoge = function(){}
for (var key in data){
console.log(data[key]);
}
// apple
// orange
// banana
// function(){}
Recommended Posts