简体   繁体   中英

Function only returns true for first element in array

I am trying to write a function that will return true if either 'purple' or 'magenta' elements are present in an array. However my code will only return true when either purple or magenta are the first item in the array:

function containsPurple(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 'purple' || arr[i] === 'magenta') {
      return true;
    }
    return false;
  }
}

So for example, containsPurple(['black', 'magenta', 'yellow']) returns false , however containsPurple(['magenta', 'black', 'yellow']) returns true . Where am I going wrong?

Consider your condition:

if (arr[i] === 'purple' || arr[i] === 'magenta') {
  return true;
}
return false;

Let's assume that arr[i] === 'orange' . Does it match your if-condition? No. So it continues to the next line, which is return false . Once a function encounters a return statement, the function is completed and the return value is returned. Never will your loop go to the next iteration, because in the first iteration it will always encounter a return statement (it be either return true or return false ).

To fix this you can move the return false outside of your loop. This way it will keep looping until any iteration matches the if condition. If not, it will exit the loop and continue to the return false and finish the function with the return value false .

 function containsPurple(arr) { for (let i = 0; i < arr.length; i++) { if (arr[i] === 'purple' || arr[i] === 'magenta') { return true; } } return false; } console.log('black, yellow', containsPurple(['black', 'yellow'])); console.log('black, magenta, yellow', containsPurple(['black', 'magenta', 'yellow'])); console.log('magenta, black, yellow', containsPurple(['magenta', 'black', 'yellow']));

That being said, in your case you can simplify your code using Array.prototype.some() :

 function containsPurple(arr) { return arr.some(element => element === 'purple' || element === 'magenta'); } console.log('black, yellow', containsPurple(['black', 'yellow'])); console.log('black, magenta, yellow', containsPurple(['black', 'magenta', 'yellow'])); console.log('magenta, black, yellow', containsPurple(['magenta', 'black', 'yellow']));

function containsPurple(arr){
    for(let i = 0; i < arr.length; i++){
        if(arr[i] === 'purple' || arr[i] === 'magenta'){
            return true;
        }
       // you're returning false after checking only the first value
       // return false;
    }
    // return false once you checked the entire array
    return false;
}

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