Javascript 函数中的奇怪行为

Strange behaviour in Javascript function

如果我在下面的代码片段中执行测试函数:

function pointInside( r, p ) {
    var result =
        ( p.x >= r.location.x - r.size.width * 0.5 ) &&
        ( p.x <= r.location.x + r.size.width * 0.5 ) &&
        ( p.y >= r.location.y - r.size.height * 0.5 ) &&
        ( p.y <= r.location.y + r.size.height * 0.5 )
    ;
    return result;
}

function test() {
    var rect = {};
    rect["location"] = { x:6, y:5 };
    rect["size"] = { width:10, height:8 };
    var p = { x:10, y:8 };
    var inside = pointInside( rect, p );
    console.log( inside ? "inside" : "outside" );
}

然后文本 "inside" 被写入控制台。伟大的。现在,如果我将 pointInside 函数更改为:

function pointInside( r, p ) {
    return
        ( p.x >= r.location.x - r.size.width * 0.5 ) &&
        ( p.x <= r.location.x + r.size.width * 0.5 ) &&
        ( p.y >= r.location.y - r.size.height * 0.5 ) &&
        ( p.y <= r.location.y + r.size.height * 0.5 )
    ;
}

然后当我调用测试函数时 "outside" 被写入控制台。在进一步调查中,我发现 pointInside 函数实际上返回未定义。为什么?我看不出 pointInside 的两个版本之间有任何有意义的区别。谁能给我解释一下?

在 javascript 中,; 是可选的(在语句末尾)...所以你的函数 returns 'undefined' (这是 false-y)和该函数中的其余代码被有效地忽略了……太棒了,不是吗!!

尝试以下方法

function pointInside( r, p ) {
    return (
        ( p.x >= r.location.x - r.size.width * 0.5 ) &&
        ( p.x <= r.location.x + r.size.width * 0.5 ) &&
        ( p.y >= r.location.y - r.size.height * 0.5 ) &&
        ( p.y <= r.location.y + r.size.height * 0.5 )
    );
}

这种愚蠢的行为可能永远无法修复,因为它会破坏太多(糟糕的)代码

不幸的是,许多 javascript 口译员试图对遗漏的分号保持宽容。如果你有 "return" 然后是行尾,许多解释器会认为你忘记了分号。因此你的 "undefined".