变量=== undefined vs. typeof variable ===" undefined" [英] variable === undefined vs. typeof variable === "undefined"

查看:109
本文介绍了变量=== undefined vs. typeof variable ===" undefined"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery核心风格指南提供了两种不同的方法来检查是否定义了变量。




  • 全局变量: typeof variable ===undefined

  • 本地变量:变量=== undefined

  • 属性: object.prop = == undefined



为什么jQuery对全局变量使用一种方法而对本地和属性使用另一种方法?对于未声明的变量, typeof foo 将返回字符串文字undefined,而身份检查 foo === undefined 会触发错误foo未定义



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


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

  • Global Variables: typeof variable === "undefined"
  • Local Variables: variable === undefined
  • Properties: object.prop === undefined

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

解决方案

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".

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

这篇关于变量=== undefined vs. typeof variable ===" undefined"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆