哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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) {
当前回答
我想要类似的东西:一个检查变量是否有有用值的函数,其中0是有用的,但空字符串、数组和对象不是(对于我的应用程序)。基于各种答案和评论,我提出了下面定义和测试的isSet()函数;对于测试值的前一半返回true,对于第二部分返回false,这正是我想要和需要的:
let fn = [1234, "1234", 0, "0", [1,2], {name: "number"}, "", [], {}, null, NaN, undefined]
console.log(fn)
const isSet = (val) => {
switch (typeof val) {
case 'number': return !isNaN(val); break; // as long as it is a number other than NaN....
case 'string': return val.length > 0; break;
case 'undefined': return false; break;
case 'object':
if (val === null) return false;
else return Object.keys(val).length > 0;
break;
}
}
for (index in fn) {
const item = fn[index];
console.log(`ind: ${index}; ${typeof item}; ${isSet(item)}`)
}
结果(在节点v16.16.0下):
[
1234,
'1234',
0,
'0',
[ 1, 2 ],
{ name: 'number' },
'',
[],
{},
null,
NaN,
undefined
]
ind: 0; number; true
ind: 1; string; true
ind: 2; number; true
ind: 3; string; true
ind: 4; object; true
ind: 5; object; true
ind: 6; string; false
ind: 7; object; false
ind: 8; object; false
ind: 9; object; false
ind: 10; number; false
ind: 11; undefined; false
其他回答
在ReactJS中,事情有点复杂!这是因为它是一个编译环境,遵循ESLint的无undef规则,因为react-scripts@2.0.3(2018年10月1日发布)。这里的文档对任何对此问题感兴趣的人都有帮助。。。
在JavaScript中,在ES6之前,变量和函数声明被提升到作用域的顶部,因此可以在代码中的正式声明之前使用标识符。。。。当ES6的[新]规则遇到对尚未声明的标识符的引用时,将发出警告。
因此,虽然有可能有一个未定义(或“未初始化”)的变量,但在ReactJS中有一个没有关闭esint规则的未声明变量是不可能的。
这可能非常令人沮丧——GitHub上有太多的项目只是利用了ES6之前的标准;并且在没有任何调整的情况下直接编译这些基本上是不可能的。
但是,对于ReactJS,可以使用eval()。如果你有一个未声明的变量,比如。。。
if(undeclaredvar) {...}
您可以简单地将此部分重写为。。。
if(eval('typeof undeclaredvar !== "undefined"')) {...}
例如。。。
if(eval(“false”)){console.log(“否!”);}if(eval(“true”)){console.log(“是!”);}
对于那些将GitHub存储库导入ReactJS项目的人来说,这只是检查是否声明了变量的唯一方法。在结束之前,我想提醒您,如果使用错误,eval()存在安全问题。
很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _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==)?
你可以试试。。。捕获块如下所示:
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')
为了检查变量是否已被声明/设置,我使用了这个肮脏的技巧。
即使使用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");
}