gpt4 book ai didi

javascript - 如何查看数组是否有值,如果有则返回 true。 - JavaScript

转载 作者:行者123 更新时间:2023-11-28 16:58:18 24 4
gpt4 key购买 nike

两个数组都包含字符串“hello”,但只有第一个数组为 true。为什么?

function containsHello(array){
for(let i = 0; i < array.length; i++){
if(array[i] === 'hello'){
return true;
} else {
return false;
}
}
}

console.log(containsHello(['hello', 'no', 'yes'])); // logs true
console.log(containsHello(['no', 'hello', 'yes'])); // logs false

最佳答案

在返回 false 的代码中,您返回得太早(在检查所有元素之前)

循环结束后应该返回 false

function containsHello(array){
for(let i = 0; i < array.length; i++){
if(array[i] === 'hello'){
return true;
}
}
return false;
}

关于javascript - 如何查看数组是否有值,如果有则返回 true。 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58439691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com