【问题标题】:nodejs object declaration and immediate shorthand if statement crashes the appnodejs 对象声明和 if 语句立即速记使应用程序崩溃
【发布时间】:2015-01-23 17:53:54
【问题描述】:

谁能给出以下 node.js 脚本崩溃的综合原因?

var _ = require("underscore");

var foo = {
  bar: 123
}

(!_.isNull(foo.bar)?foo.bar = true:"");

它产生的错误是:

TypeError: Cannot read property 'bar' of undefined
    at Object.<anonymous> (/Users/blahsocks/test_ob.js:7:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

我可以通过在“if”之前添加 console.log(foo) 来解决此问题,或者如果我将 if 更改为 (typeof ob.bar !== "null"),但我想知道这是否会导致错误。

【问题讨论】:

    标签: javascript node.js uncaught-exception typeerror


    【解决方案1】:

    Automatic semicolon insertion 打到你了。

    您的代码被解释为

    var foo = {
      bar: 123
    }(   !_.isNull(foo.bar)?foo.bar = true:""  );
    

    这是赋值中的函数调用。甚至在您收到 {bar:123} 不是函数的错误之前,您就会遇到异常,因为您正在访问 foo 上的属性,然后才为其分配值(并且仍然是 undefined)。

    要解决此问题,请使用

    var foo = {
      bar: 123
    };
    
    !_.isNull(foo.bar)?foo.bar = true:"";
    

    (分号和省略括号都可以单独解决问题)。

    【讨论】:

    • 非常感谢,我多年来一直这样编码,但从未遇到过这个问题(幸运的是)。
    【解决方案2】:

    问题就在这里:

    (!_.isNull(foo.bar)?foo.bar = true:"");

    该语句没有意义,我认为您不能在内联 if 语句中分配属性。我也不知道你为什么要用true 覆盖123

    尽管如此,您似乎想要做的事情应该可以通过以下方式完成:

    foo.bar = (!_.isNull(foo.bar) ? true : "");
    

    【讨论】:

    • 这只是手头问题的一个非常简单的例子,没有理由不能在 if 中分配变量。我知道如果您描述的问题是对象声明一开始没有被识别,我可以达到相同的结果。您可以向对象添加另一个变量并为其分配不同的值,但仍然存在相同的问题。
    猜你喜欢
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    相关资源
    最近更新 更多