这是我的测试:
var test = function () {
$.each([1, 2], function () {
if(true !== false) { // it is just an example
alert('I am here');
return false; // how should I make the function test to stop or to exit here?
}
});
return true;
};
alert(test());
我希望 test
函数返回 false,但它返回 true。
为什么?我应该如何修复代码?请参阅评论了解更多详情。
最佳答案
从 .each()
回调中返回 false
只会停止 .each()
迭代。它不从封闭函数返回;在 JavaScript 中做到这一点的唯一方法是抛出异常。
你可以做的是设置一个标志:
var test = function () {
var abort = false;
$.each([1, 2], function () {
if(true !== false) { // it is just an example
alert('I am here');
abort = true;
return false; // how should I make the function test to stop or to exit here?
}
});
return !abort;
};
关于javascript - 为什么这个函数返回 true 而不是 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12849105/