简体   繁体   中英

If statement not working inside foreach loop javascript

I am trying to return the first value which is greater than 25 from an array, without using other methods such as filter. Assume the array is always sorted.

The function always returns undefined. Why is that happening? Here is the code:

 function checkArr(arr){ arr.forEach(i => { if (i>25) return i; }) } console.log(checkArr([10,20,34,45]))

The output should be 34.

When you use forEach , you execute another function for every item in the array. That function can return a value just fine, but it'll get completely ignored. If you want to return a value in the checkArr function, you have to do something like this:

function checkArr(arr) {
  for (let i of arr) {
    if (i>25) return i;
  }
}

You can use find function instead of forEach . And you must return a result of this function to get an answer instead of undefined .

 function checkArr(arr) { return arr.find(i => i > 25); } console.log(checkArr([10,20,34,45])) 

forEach function returns nothing, it just makes some actions for each element in an array.

Your function is not returning anything. And returning inside a forEach won't have any effect, since forEach always returns undefined . You can use a simple while loop to do this:

 function checkArr(arr){ var i = 0; while (i<arr.length) { if (arr[i]>25) return arr[i]; i++; } return null; // if no entry is greater than 25 } console.log(checkArr([10,20,34,45])); 

The forEach() method executes a provided function once for each array element.

From the above statement it is clear that you can not return from the middle of the execution of the loop.

Use for...of loop instead to return as soon as the condition is true :

 function checkArr(arr){ for(var item of arr){ if (item > 25) return item; } } console.log(checkArr([10,20,34,45])) 

Seems like you're looking for find :

 function checkArr(arr) { return arr.find(i => i>25); } console.log(checkArr([10,20,34,45])); 

It's because you're passing a delegate function when calling .forEach .

The return of the delegate is getting lost and isn't applying to anything. To get your desired result, you'll want to exit the calling function checkArr .

This can be done using a simple for loop.

 function checkArr(arr){ for (var i = 0; i < arr.length++; i++) { if (arr[i] > 25) return arr[i]; } } console.log(checkArr([10,20,34,45])) 

This approach also supports older browsers, unlike some, every and forEach

function checkArr(arr){
    return arr.filter(m => m > 25)
}
checkArr([10,20,34,45]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM