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']));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…