简体   繁体   中英

Using a for-loop to find a string in an array is working, but forEach() does not here. Why and how to correct?

Working through some javascript array exercises to solidify my understanding. Came across an exercise that I'm able to solve easily using a for-loop, but not using the forEach() method. Why is happening, and how would I correct for this?

Here's the exercise question listed out, and my code using both methods below: "Write a function that takes an array of values and returns an boolean representing if the word "hello" exists in the array."

 function hello_exists(array){ for(i = 0; i < array.length; i++){ if(array[i] === "hello"){ return true } } } var my_arr = ["some", "hello", "is", "cat"] hello_exists(my_arr) // returns true as expected function hello_exists(array){ array.forEach(function(val){ if(val === "hello") { return true } }) } var my_arr = ["some", "hello", "is", "cat"] hello_exists(my_arr) // returns undefined. not sure why? 

Returning true in forEach does not actually return a value to the caller and has no effect.

The callback passed into forEach is designated to perform a set of operations in iteration(without returning anything)

Use a variable to return after the forEach has finished executing

function hello_exists(array){
  var exists = false;
  array.forEach(function(val){
    if(val == "hello"){
         exists = true;
    }
  });
  return exists;
}

As an alternative, you can use some()

function hello_exists(array){
  return array.some(function(val){
    return val == "hello";
  });
}

or filter() with checking the length on the results

function hello_exists(array){
  return array.filter(function(val){
    return val == "hello";
  }).length > 0;
}

Your second hello_exists function is not returning anything. It may look like it is because you have the 'return' in there, but that is in the forEach function.

In the second example, you need to return something for the hello_exists function. Something like this would work

function hello_exists(array){
  var isTrue = false
  array.forEach(function(val){
    if(val === "hello") {
      isTrue = true
    }
  })
  return isTrue
}
var my_arr = ["some", "hello", "is", "cat"]

hello_exists(my_arr) // true

It can also help to understand what's happening if you imagine a simplified implementation of forEach :

function forEach(array, fn) {
    var i;
    for (i = 0; i < array.length; i++) {
        fn(arr[i]);  // forEach doesn't care about what the function returns
    }
}

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