I'm using this JavaScript to iterate through an array and find a matching array element:
var remSize = [],
szString, remData, remIndex, i;
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
remSize[i].size == remData.size ? remIndex = i : remIndex = -1;
}
The array contains these "sizes": ["34", "36", "38"...]
.
remData.size
is the "size" I'm looking for (e.g. "36").
I need to return the index i
if the size I'm searching for is in the index. Otherwise I need to return -1
. Is there a better way to do this?
This question is related to
javascript
for-loop
I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])
It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.
<array>
is the array to look through, <element>
is the value you are looking for, and [fromIndex]
is the index to start from (defaults to 0).
I hope this helps reduce the size of your code!
The logic is incorrect. It would always return the result of last element in the array.
remIndex = -1;
for (i = 0; i < remSize.length; i++) {
if (remSize[i].size == remData.size) {
remIndex = i
break;
}
}
Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
let arr = [1,2,3,4,5];
for (let ele of arr) {
if (ele > 3) break;
console.log(ele);
}
Source: Stackoverflow.com