javascript - 为什么这个函数返回 true 而不是 false

标签 javascript jquery

这是我的测试:

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/

相关文章:

javascript - 我的 AJAX post 变量无法访问我的 PHP

javascript - xml 到 json 转换中不需要的字段?

javascript - 如何在调用post方法时将jquery变量传递给html

javascript - 什么是空?在这行 JavaScript 中做的事情

javascript - Node.js 单击按钮并使用 TCP/IP 协议(protocol)发送内容

javascript - 在 javascript 被阻止时保持 google chrome 扩展 ContentScripts 正常工作

jquery - 当宽度设置为自动时,对话框的最大宽度不受影响

javascript - Angular 发布请求不起作用不起作用

javascript - jQuery - 和运算符

javascript - 未捕获的 InvalidStateError : Failed to execute 'dispatchEvent' on 'EventTarget' : The event provided is null