我有一个数组。我有一个函数来检查数组是否包含数字'2'。退货退出功能
如果找到这个数字,我希望函数返回true。如果不是,它应该返回false。
我写了这个:
function hasTwo(arr) {
arr.forEach((x) => {
if (x === 2) {
console.log("Two!")
return true
}
})
console.log("No two :(")
return false
}
let arr = [1,2,3,4,5,6]
console.log(hasTwo(arr))
我的期望是,在第二一个foreach迭代,如果条件得到满足,函数将返回true。
然而,这是控制台输出:
Two!
No two :(
false
我认为,第一return语句从条件块,不封闭函数返回。 (是吗?)
我已经重写的功能与一个变量来存储返回值:
function hasTwo(arr) {
let result = false
arr.forEach((x) => {
if (x === 2) {
console.log("Two!")
result = true
}
})
return result
}
但我没有看到持续的,如果X功能点=== 2条件已被满足。有没有办法返回一个值并立即退出函数?
你在回调函数中返回值 –
为什么不使用'.filter()'? – evolutionxbox
@evolutionxbox:因为过滤器不会退出迭代吗? – Bergi