任何人都可以给出一个全面的理由,为什么以下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")
但是我想知道是否存在导致错误的原因。
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:"";
(分号和省略括号都可以解决问题)。
问题在这里:
(!_.isNull(foo.bar)?foo.bar = true:"");
这句话毫无意义,我认为你不能在内联if语句中分配一个属性。我也不知道你为什么试图用123
覆盖true
。
尽管如此,你似乎要做的事情应该是可以实现的:
foo.bar = (!_.isNull(foo.bar) ? true : "");