简体   繁体   中英

Why does my for loop return the correct answer, but my forEach does not?

this is my first question on SO. I have an assignment where I'm supposed to create a function that has two parameters--the first being an array of strings, and the second being a string to possibly match in the array.

I have two variations of the function: one uses a "for" loop, the other uses the .forEach() method. The for loop accurately returns "true"/"false" depending on whether or not the second parameter exists within the array. The forEach always returns "false".

Can someone explain why? Code below:

.forEach() version:

function insideArray (array, word) {
  var value;
  array.forEach(function(each) {
    if(each === word) {
      value = "true";
      return value;
    }
    else {
      value = "false";
    }
  });
  return value;
}

for loop version:

function insideArray (array, word) {
  var value;
  for(var i = 0; i < array.length; i++) {
    if(array[i] === word) {
      value = "true";
      return value;
    }
    else {
      value = "false";
    }
  }
  return value;
}

A sample array:

var heroArray = [ "spiderman", "wolverine", "batman", "greenArrow", "boosterGold" ];

Testing .forEach():

insideArray(heroArray, "spiderman");
"false"

Testing for loop:

insideArray(heroArray, "spiderman");
"true"

Thanks for any help in advance!

This happens because you are returning from callback function of forEach and not from insideArray() so in the end insideArray() will always return false except in the case you match the last element in the array. you can fix the code by initializing value with false and removing else condition like this:

function insideArray (array, word) {
  var value = "false";
  array.forEach(function(each) {
    if(each === word) {
      value = "true";
    }
  });
  return value;
}

Also note that you can write more simple code for this by using indexOf :

function insideArray (array, word) {
  return array.indexOf(word) >= 0 ? "true" : "false";
}

The .forEach method doesn't return anything, so I'd modify your code to the following:

function insideArray (array, word) {
  var value = "false";
  array.forEach(function(each) {
    if(each === word) {
      value = "true";
    }
  });
  return value
};

You can't break / return out of a Array#forEach loop, though you could throw and catch from it (but don't). Array#some would probably be a better choice, if you intend to test like that. A better, though slightly less well supported, method would be to use Array#includes ( polyfills are available , or transpile with babel ). Another solution would be Array#indexof

 function insideArray(array, word) { return String(array.some(function(each) { return each === word; })); } var heroArray = ['spiderman', 'wolverine', 'batman', 'greenArrow', 'boosterGold']; console.log(insideArray(heroArray, 'supergirl')); console.log(insideArray(heroArray, 'batman')); 

 const insideArray = (array, word) => String(array.includes(word)); const heroArray = ['spiderman', 'wolverine', 'batman', 'greenArrow', 'boosterGold']; console.log(insideArray(heroArray, 'supergirl')); console.log(insideArray(heroArray, 'batman')); 

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