Javascript函数中的奇怪行为

R E*_*rth 11 javascript expression boolean

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

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" );
}
Run Code Online (Sandbox Code Playgroud)

然后文本"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 )
    ;
}
Run Code Online (Sandbox Code Playgroud)

然后当我调用测试函数"outside"时,会将其写入控制台.在进一步调查中,我发现pointInside函数实际上是返回undefined.为什么?我看不出pointInside的两个版本之间有任何有意义的区别.任何人都可以向我解释这个吗?

Jar*_*a X 11

在javascript中,;是可选的(在语句结束时)...所以你的函数返回'undefined'(这是假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 )
    );
}
Run Code Online (Sandbox Code Playgroud)

它可能永远不会被修复,这种愚蠢的行为,因为它会破坏太多(差)代码


Max*_*phy 8

不幸的是,许多javascript口译员试图原谅丢失的分号.如果你有"返回"然后是行尾,许多口译员都会认为你忘记了分号.因此你的"未定义".

  • 这是规范的一部分,它不是"许多口译员试图做的事情",它是*所有*口译人员必须做的事情. (6认同)