最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

nodejs对象声明和即时简写if语句崩溃应用程序

运维笔记admin13浏览0评论

nodejs对象声明和即时简写if语句崩溃应用程序

nodejs对象声明和即时简写if语句崩溃应用程序

任何人都可以给出一个全面的理由,为什么以下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:"";

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

发布评论

评论列表(0)

  1. 暂无评论