Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65902660/function-only-returns-true-for-first-element-in-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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']));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...