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.
Looping through arrays and adding by index to another array
If I don't misunderstood your required output then you can use two foreach()
to iterate every nested array and push every element by their index position of all nested array.
$_GET = [
"rentalPropertyAddress"=>["111 tree st","112 tree st","122 tree st"],
"gasInitialized"=>["on","on","off"],
"waterInitialized"=>["off","on","on"],
"electricInitialized"=>["on","on","off"],
"inspectionDate"=>["","",""],
"rentalDate"=>["","",""],
"vacantInitialized"=>["no","no","yes"]
];
$retval = [];
foreach ($_GET as $key => $item) {
$i=0;
foreach($item as $k=>$v){
$retval[$i][] = $v;
$i++;
}
}
echo "<pre>";
print_r($retval);
echo "</pre>";
DEMO: https://3v4l.org/LrpGo
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.
Javascript getting an array from the index of another array
You could collect all indices in an object with the color as property.
This approach features
a classic
for
statement for iterating the index,a logical nullish assignment
??=
to check the property and assign an array if not given,and
Array#push
, to get the index into the array with the color as name.
const
colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'],
indices = {};
for (let i = 0; i < colors.length; i++) {
(indices[colors[i]] ??= []).push(i);
}
console.log(indices);
How to turn around the content of an array to another array with a forEach-Loop?
Ok so Issue is your forEach
which not running with oldArray
length
mean 5 times
Why this is happening? It is because you are poping out value withing forEach
which change the length and data of forEach
.
You can check by putting console.log(oldArray);
in forEach
.
var arrayA = ["h", "e", "l", "l", "o"];var arrayB = [];
function copyArray(oldArray, newArray) { var length = oldArray.length; for (var i = 0; i < length; i++) { var storeElement = oldArray.pop(); newArray.push(storeElement); }; console.log(oldArray + " old array"); console.log(newArray + " new array");}
copyArray(arrayA, arrayB);
var reverseArray = ["h", "e", "l", "l", "o"].reverse();
console.log("reverse array");
console.log(reverseArray);
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>
How to find the foreach index?
foreach($array as $key=>$value) {
// do stuff
}
$key
is the index of each $array
element
Related Topics
How to Put View on Top of All Other Views in Swiftui
Viewwilllayoutsubviews in Swift
Scrolltoitem at Indexpath at .Top Hides Cell Under Header When Sectionheaderspintovisiblebounds
Swift Navigation Bar Item Not Calling Action
Implement Protocol with Different Associated Type
Pfobject Unable to Be Cast to Custom Subclass
"The Requested Snapshot Version Is Too Old." Error in Firestore
Swift Increment Int! Not Working
Difference Between Object(Forkey:) and Value(Forkey:) in Userdefaults
Swiftui CPU High Usage on Real-Time Foreach View Updating (Macos)
Set an Horizontal Scroll to My Barchart in Swift
How to Get Access Token from Instagram API
Calling Git Commands from Within a Swift Macos Application
How to Group Items in a Nspopupbutton
How to Use Axobserveraddnotification in Swift
Swiftui - Button - How to Pass a Function (With Parameters) Request to Parent from Child