哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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) {
当前回答
我很惊讶这还没有被提及。。。
以下是使用此['var_name']的一些其他变体
使用此方法的好处是,它可以在定义变量之前使用。
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
其他回答
我根据对象使用两种不同的方式。
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
有时我不想将空字符串求值为false,所以我使用这种情况
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
如果你需要相反的东西,那么首先!变量变为!!变量,并且在无效函数中==变为!=函数名变为notInvalid。
最高答案是正确的,请使用typeof。
然而,我想指出的是,在JavaScript中,undefined是可变的(出于某种不道德的原因)。所以只需检查varName!==undefined有可能不会总是像您期望的那样返回,因为其他库可能已经更改了undefineed。一些答案(比如@skalee's)似乎更倾向于不使用typeof,这可能会让人陷入麻烦。
处理此问题的“旧”方法是将undefined声明为一个var,以抵消任何潜在的undefined/override。然而,最好的方法仍然是使用typeof,因为它将忽略其他代码中对undefined的任何重写。特别是如果你正在编写代码,以供在野外使用,谁知道页面上还有什么其他内容。。。
如何检查变量是否存在
这是一个非常可靠的解决方案,用于测试变量是否存在并已初始化:
var setOrNot = typeof variable !== typeof undefined;
它最常用于与三元运算符结合使用,以在某个变量尚未初始化的情况下设置默认值:
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";
封装问题
不幸的是,您不能简单地将检查封装在函数中。
你可能会想到这样做:
function isset(variable) {
return typeof variable !== typeof undefined;
}
然而,如果您正在调用例如isset(foo),并且尚未定义变量foo,这将产生引用错误,因为您无法将不存在的变量传递给函数:
未捕获引用错误:未定义foo
测试函数参数是否未定义
虽然我们的isset函数不能用于测试变量是否存在(原因如上所述),但它确实允许我们测试函数的参数是否未定义:
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
即使没有将y的值传递给函数测试,我们的isset函数在这种情况下也能很好地工作,因为在函数测试中y是一个未定义的值。
在JavaScript中,可以定义变量,但保持值未定义,因此最常见的答案在技术上不正确,而是执行以下操作:
if (typeof v === "undefined") {
// no variable "v" is defined in the current scope
// *or* some variable v exists and has been assigned the value undefined
} else {
// some variable (global or local) "v" is defined in the current scope
// *and* it contains a value other than undefined
}
这可能足以满足你的目的。以下测试具有更简单的语义,这使得准确描述代码的行为并自己理解它变得更容易(如果您关心这些事情):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
当然,这假设您在浏览器中运行(其中window是全局对象的名称)。但如果你在摆弄这样的全局变量,你很可能是在浏览器中。主观上,在window中使用“name”在风格上与使用window.name来引用全局变量一致。将全局变量作为窗口的财产而不是变量进行访问,可以最大限度地减少代码中引用的未声明变量的数量(为了linting的好处),并避免全局变量被局部变量遮蔽的可能性。此外,如果全局对象使您的皮肤爬行,您可能会觉得仅用这根相对较长的棍子触摸它们更舒服。
为了检查变量是否已被声明/设置,我使用了这个肮脏的技巧。
即使使用eval,我也没有找到将代码提取到函数的方法。点击下面的评论,了解原因。
"use strict";
// var someVar;
var declared;
try {
someVar;
declared = true;
} catch(e) {
declared = false;
}
if (declared) {
console.log("someVar is declared; now has the value: " + someVar);
} else {
console.log("someVar is not declared");
}