哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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) {
当前回答
您需要运算符的类型。明确地:
if (typeof variable !== 'undefined') {
// the variable is defined
}
其他回答
这取决于您是否只关心变量是否已定义,或者是否希望它具有有意义的值。
检查类型是否未定义将检查变量是否已定义。
==空或!==null将仅检查变量的值是否完全为null。
==空或!=null将检查该值是否未定义或为null。
if(value)将检查变量是否为undefined、null、0或空字符串。
你可以试试。。。捕获块如下所示:
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')
在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的好处),并避免全局变量被局部变量遮蔽的可能性。此外,如果全局对象使您的皮肤爬行,您可能会觉得仅用这根相对较长的棍子触摸它们更舒服。
我更喜欢这种方法,因为它的准确性和简洁性:
变量x如果(x===无效0){console.log(“x未定义”)}其他{console.log(“x已定义”)}
正如在其他评论和回答中提到的,undefined不能保证是undefineed。因为它不是关键字,所以可以在全局范围以外的范围中将其重新定义为变量。这里有一个小例子可以说明这种细微差别:
var undefined='bar'console.log(`在全局范围内:${undefined}`)函数foo(){var undefined=“已定义”变量x如果(x===未定义){console.log(`x===undefined`)}其他{console.log(`x!==undefined`)}如果(x===无效0){console.log(`x===void 0`)}其他{console.log(`x!==void 0`)}}foo()
请参阅void以了解兼容性(IE5支持!?!!哇!)。
为了使if条件正确工作,我们必须使用关键字let来创建变量。
let name = undefined;
if (name) {
alert('valid')
};