Express,EJS,testing未定义的挑战

我使用express框架创build了一个简单的nodejs网站,使用couchdb创build数据库,使用EJS创build模板。 有些时候,我的一些字段在我的一些JSON文档中是空的或未定义的,我需要处理它。

<% if (typeof test !== 'undefined') { %> <p><%= test %></p> <% } %> 

这段代码似乎处理“testing”字段未定义就好,但下面的代码会抛出一个错误,说'testing是未定义'

 <% if (test) { %> <p><%= test %></p> <% } %> 

为什么JavaScript不明白testing是未定义的,然后把if语句放在false?

因为“未定义”的概念与JavaScript语言中定义的variables的状态不同。 原因是可以理解的,但效果可能会令人困惑,尤其是variables名称与对象属性。

你已经演示了如何试图访问未定义的variables将引发exception。 不要将这个状态(一个未定义的variables)与“未定义”types混淆:

 if (bogusVariable) { // throws ReferenceError: bogusVariable is not defined. typeof(bogusVariable); // => undefined - wow, that's confusing. 

但是,未定义对象的属性可以安全地进行testing:

 var x = {}; // an object x.foo; // => undefined - since "x" has no property "foo". typeof(x.foo); // => undefined if (!x.foo) { /* true */ } 

注意到所有variables实际上是“全局”对象(在Web浏览器中是“全局”或“窗口”)的属性,都可以利用这个属性。

 bogus; // => ReferenceError: bogus is not defined. global.bogus; // => undefined (on node/rhino) window.bogus; // => undefined (on web browsers) 

所以你可以这样编写你的EJS代码:

 <% if (global.test) { %> <p><%= test %></p> <% } %> 

是的,这与JavaScript语言的许多部分一样令人困惑。

大多数语言是这样的:

  irb >> foo NameError: undefined local variable or method `foo' for main:Object from (irb):1 

要检查testing是否被定义,你需要这样做:

 <% if (this.test) { %> here, test is defined <% } %>