哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
typeof运算符将检查变量是否真的未定义。
if (typeof variable === 'undefined') {
// variable is undefined
}
与其他运算符不同,typeof运算符在与未声明的变量一起使用时不会引发ReferenceError异常。
但是,请注意,typeof null将返回“object”。我们必须小心避免将变量初始化为null的错误。为了安全起见,我们可以使用以下方法:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
有关使用严格比较==而不是简单相等==的更多信息,请参阅:JavaScript比较中应该使用哪个相等运算符(==vs==)?
其他回答
if (variable === undefined) {}
工作正常,只检查未定义。
Null是JavaScript中的值,typeof Null返回“object”
因此,如果您传递空值,则接受的答案将不起作用。如果传递空值,则需要为空值添加额外的检查:
if ((typeof variable !== "undefined") && (variable !== null))
{
// the variable is defined and not null
}
你可以试试。。。捕获块如下所示:
var status='变量存在'尝试{我的变量}catch(ReferenceError){status='变量不存在'}console.log(状态)
缺点是不能将其放在函数中,因为它会引发ReferenceError
函数变量Exists(x){var状态=真尝试{x(x)}catch(ReferenceError){状态=假}返回状态}console.log(variableExists(x))
编辑:
如果您在前端Javascript中工作,需要检查变量是否未初始化(var x=undefined将算作未初始化),可以使用:
函数globalVariableExists(变量){if(window[variable]!=未定义){返回true}return false}var x=未定义console.log(globalVariableExists(“x”))console.log(globalVariableExists(“y”))变量z=123console.log(globalVariableExists(“z”))
编辑2:
如果需要检查当前作用域中是否存在变量,只需将其与字符串中包含的变量名称一起传递给函数即可:
函数variableExists(变量,thisObj){if(thisObj[variable]!==未定义){返回true}return false}类someClass{构造函数(名称){这个.x=99这个。y=99这个.z=99这个。v=99console.log(variableExists(name,this))}}新建someClass('x')新建someClass('y')新建someClass('z')新建someClass('v')新建someClass('doesNotExist')
很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。
假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?
或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?
我们通过使用最强大的JasvaScript运算符in运算符来实现
"[variable||property]" in [context||root]
>> true||false