Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - 变量===未定义vs. typeof变量===“未定义”(variable === undefined vs. typeof variable === “undefined”)

The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

(jQuery Core Style Guidelines提出了两种不同的方法来检查变量是否已定义。)

  • Global Variables: typeof variable === "undefined"

    (全局变量: typeof variable === "undefined")

  • Local Variables: variable === undefined

    (局部变量: variable === undefined)

  • Properties: object.prop === undefined

    (属性: object.prop === undefined)

Why does jQuery use one approach for global variables and another for locals and properties?

(为什么jQuery为什么对全局变量使用一种方法而对局部变量和属性使用另一种方法?)

  ask by Patrick McElhaney translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For undeclared variables, typeof foo will return the string literal "undefined" , whereas the identity check foo === undefined would trigger the error "foo is not defined" .

(对于未声明的变量, typeof foo将返回字符串文字"undefined" ,而身份检查foo === undefined将触发错误“ foo not defined” 。)

For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.

(对于局部变量(您知道已在某处声明),不会发生此类错误,因此进行身份检查。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...