我已经验证了,在某些情况下,第一个if条件为真。函数不应该返回true并停止执行吗?但是,在这种情况下,即使在第一个if条件为true之后,函数也会继续执行,直到forEach循环结束,然后退出,每次返回false。谁能告诉我错误在哪里?
function checkValid(id){
pressedButtons.forEach(button => {
console.log(`ID: ${id} and Button: ${button}`)
if (id == button+1 || id == button+8 || id == button-1 || id == button-8){
console.log("IM HERE")
return true
}
})
return false
}发布于 2017-04-07 00:28:19
问题似乎是function scoping/closures的问题
我添加了一个"isValid“变量,它将在整个forEach函数中保持”有效性“。button => {}是一个有自己作用域的函数,它在每个pressedButtons上运行。仅从限定了作用域的函数返回return true,而不从checkValid函数返回。
function checkValid(id){
var isValid = false;
pressedButtons.forEach(button => {
console.log(`ID: ${id} and Button: ${button}`)
if (id == button+1 || id == button+8 || id == button-1 || id == button-8){
console.log("IM HERE")
isValid = true;
}
})
return isValid;
}发布于 2017-04-07 00:29:25
你可以使用Promises来停止foreach循环。
function checkValid(id){
var promises= [];
pressedButtons.forEach(button => {
return new Promise(function(resolve, reject){
console.log(`ID: ${id} and Button: ${button}`)
if (id == button+1 || id == button+8 || id == button-1 || id == button-8){
console.log("IM HERE")
resolve(true);
}
});
});
Promise.race(promises).then(function(result){
// as soon as any promise resolves it will fall here
});}
https://stackoverflow.com/questions/43260680
复制相似问题