Get loop counter/index using for…of syntax in JavaScript
for…in
iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach
method that passes both the value and the index to the function you give it:
var myArray = [123, 15, 187, 32];
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32
Or ES6’s Array.prototype.entries
, which now has support across current browser versions:
for (const [i, value] of myArray.entries()) {
console.log('%d: %s', i, value);
}
For iterables in general (where you would use a for…of
loop rather than a for…in
), there’s nothing built-in, however:
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);
}
demo
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.
How do you get the index of the current iteration of a foreach loop?
The foreach
is for iterating over collections that implement IEnumerable
. It does this by calling GetEnumerator
on the collection, which will return an Enumerator
.
This Enumerator has a method and a property:
MoveNext()
Current
Current
returns the object that Enumerator is currently on, MoveNext
updates Current
to the next object.
The concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.
Get index in ForEach in SwiftUI
This works for me:
Using Range and Count
struct ContentView: View {
@State private var array = [1, 1, 2]
func doSomething(index: Int) {
self.array = [1, 2, 3]
}
var body: some View {
ForEach(0..<array.count) { i in
Text("\(self.array[i])")
.onTapGesture { self.doSomething(index: i) }
}
}
}
Using Array's Indices
The indices
property is a range of numbers.
struct ContentView: View {
@State private var array = [1, 1, 2]
func doSomething(index: Int) {
self.array = [1, 2, 3]
}
var body: some View {
ForEach(array.indices) { i in
Text("\(self.array[i])")
.onTapGesture { self.doSomething(index: i) }
}
}
}
How can i get index use forEach loop?
You can simply use a for
loop and use classList.contains()
to check if the class is present. Also, you need to declare a local var, to store the index returned from the loop.
const product = document.querySelector(".product");
const productList = product.querySelectorAll("li");
function getIdx() {
let idx;
for (var i = 0; i < productList.length; i++) {
let list = productList[i];
if (list.classList.contains("on")) {
idx = i;
}
}
return idx;
};
function printIdx() {
let idx = getIdx();
console.log(idx);
}
productList.forEach(list => {
list.addEventListener("click", printIdx);
});
<ul class="product">
<li>aaaaa</li>
<li>bbbbb</li>
<li class="on">ccccc</li>
<li>ddddd</li>
</ul>
Automatically get loop index in foreach loop in Perl
Like codehead said, you'd have to iterate over the array indices instead of its elements. I prefer this variant over the C-style for
loop:
for my $i (0 .. $#x) {
print "$i: $x[$i]\n";
}
How to find the foreach index?
foreach($array as $key=>$value) {
// do stuff
}
$key
is the index of each $array
element
How to target specific index with forEach array method?
You can remove element
from setInterval
because inner function setInterval
has an access to the variables of outer function such as element
. Such behavior is called closure.
In addition, it is possible to use arrow functions to make shorter and cleaner your code. Moreover, arrow functions:
An arrow function does not have its own this. The this value of the
enclosing lexical scope is used; arrow functions follow the normal
variable lookup rules.
sentinel.forEach((element, index) => {
setInterval(() =>{
if (index === 0){
console.log(element);
}
}, 3000);
ForEach - Index out of range?
Let me give you a simple example to show you what happened:
struct ContentView: View {
@State private var lowerBound: Int = 0
var body: some View {
ForEach(lowerBound..<11) { index in
Text(String(describing: index))
}
Button("update") { lowerBound = 5 }.padding()
}
}
if you look at the upper code you would see that I am initializing a ForEach JUST with a Range like this: lowerBound..<11
which it means this 0..<11
, when you do this you are telling SwiftUI, hey this is my range and it will not change! It is a constant Range! and SwiftUI says ok! if you are not going update upper or lower bound you can use ForEach without showing or given id
! But if you see my code again! I am updating lowerBound of ForEach and with this action I am breaking my agreement about constant Range! So SwiftUI comes and tell us if you are going update my ForEach range in count or any thing then you have to use an id
then you can update the given range! And the reason is because if we have 2 same item with same value, SwiftUI would have issue to know which one you say! with using an id
we are solving the identification issue for SwiftUI! About id you can use it like this: id:\.self
or like this id:\.customID
if your struct conform to Hash-able protocol, or in last case you can stop using id if you confrom your struct to identifiable protocol! then ForEach would magically sink itself with that.
Now see the edited code, it will build and run because we solved the issue of identification:
struct ContentView: View {
@State private var lowerBound: Int = 0
var body: some View {
ForEach(lowerBound..<11, id:\.self) { index in
Text(String(describing: index))
}
Button("update") { lowerBound = 5 }.padding()
}
}
Using Indices to get Index in a ForEach loop SwiftUI
In the variant of indices
, you should use self
as id
ForEach(self.postViewModel.posts.indices, id: \.self) { post in
Possible variant to have both
ForEach(Array(self.postViewModel.posts.enumerated()),
id: \.1.postId) { (index, post) in
Java8 forEach with index
I found a util method in eclipse collections with this post Is there a concise way to iterate over a stream with indices in Java 8?
https://www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/impl/utility/Iterate.html#forEachWithIndex-java.lang.Iterable-org.eclipse.collections.api.block.procedure.primitive.ObjectIntProcedure-
Iterate.forEachWithIndex(people, (Person person, int index) -> LOGGER.info("Index: " + index + " person: " + person.getName()));
The implementation https://github.com/eclipse/eclipse-collections/blob/master/eclipse-collections/src/main/java/org/eclipse/collections/impl/utility/internal/IteratorIterate.java is very similar to my util method:
public static <T> void forEach(@NonNull Iterable<T> iterable, @NonNull ObjIntConsumer<T> consumer) {
int i = 0;
for (T t : iterable) {
consumer.accept(t, i++);
}
}
Related Topics
Why Does System.Threading.Timer Stop on Its Own
Using Moq to Mock an Asynchronous Method for a Unit Test
Finding Property Differences Between Two C# Objects
Auto-Resize Multiple Forms Rendered on Panel
Why Do C#'s Binary Operators Always Return Int Regardless of the Format of Their Inputs
How to Define Properties in Partial Classes, Then Mark Them with Attributes in Another Partial Class
Convert List to Dictionary Using Linq and Not Worrying About Duplicates
Async/Await - Is It *Concurrent*
How to Generate Random Color Names in C#
Unit Testing That Events Are Raised in C# (In Order)
A Pattern for Self-Cancelling and Restarting Task
Using Ssl and Sslstream for Peer to Peer Authentication
Why Does the Is Operator Return False When Given Null
How to Add Code Outside the Scope of Main When Using C# 9 Top Level Statements
The Bare Minimum Needed to Write a Msmq Sample Application
In What Areas Might the Use of F# Be More Appropriate Than C#