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

Lor*_*ard 1 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());
Run Code Online (Sandbox Code Playgroud)

我希望test函数返回false但它返回true.
为什么?我该如何修复代码?请参阅评论以获取更多详细信息.

Poi*_*nty 13

false.each()回调中返回只是暂停.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;
}?;
Run Code Online (Sandbox Code Playgroud)