如何在node.js中停止接收ReferenceError错误?

3
    183|             });
    184| 
 >> 185|             <% if(just_registered) { %>
    186|                 alert("Welcome!");
    187|             <% } %>
    188| 

just_registered is not defined

基本上,我想说:如果just_registered被定义并且为真,则弹出警报。然而,我不想设置所有内容为false……我只想让它未定义(我有大约100个变量)。
1个回答

9

<% if(typeof just_registered !== "undefined") { %>

这段代码的作用是检查本地变量是否存在。为了实现这一点,您必须使用 typeof 运算符,因为访问未声明的本地变量 just_registered 会创建一个引用错误。

这最好与以下内容进行比较:

var foo;
if (foo) { }

vs

//var foo;
if (foo) { } // ReferenceError

Where as

//var foo
if (typeof foo !== "undefined") { } 

会起作用,因为使用 typeof 运算符访问未声明的变量只会返回 "undefined" 而不是抛出 ReferenceError 异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接