如何解决如何检查变量是否未定义与未在javascript中声明?
我知道要查找JavaScript中是否未声明变量,可以使用factory1<T>(ctor?: NoParamConstructor<T>):T{return new ctor};
let a=this.factory<T>()
。如果我将变量声明为未定义(if (typeof variable === 'undefined')
),则if语句仍返回true。在JavaScript中,是否有可能发现未声明的变量与值为undefined的变量之间的区别?我知道它们很相似,但是先做var variable = undefined
然后再做const variable = undefined
会引发错误,因此它们必须不同。
variable = "something else"
我不想使用try catch块,因为我希望能够基于此分配另一个常量。我想要一个这样的解决方案:const variable = undefined
if (typeof variable === 'undefined') {
console.log('"variable" is undefined')
}
if (typeof undeclaredVariable === 'undefined') {
console.log('"undeclaredVariable" is undefined')
}
,除了const isVariableDeclared = variable === undeclared
在javascript中不存在。我知道我可以在try catch块中使用let,但是我正在寻找更优雅的东西。
解决方法
至少在撰写本文时...不,看来您不能做这样的事情:
var a = undeclared(var) ? 'undeclared' : 'undefined'
原因是您不能将未声明的变量传递给函数;即使在非严格模式下,它也会引发错误。
我们能做的就是:
var barIsDeclared = true;
try { bar; }
catch (e) {
if (e.name == "ReferenceError") {
barIsDeclared = false;
}
}
console.log(barIsDeclared);
为什么?
未定义:在声明了变量但未声明变量时发生 被分配了任何值。未定义不是关键字。
未声明:当我们尝试访问任何未声明的变量时会发生 之前使用var或const关键字初始化或声明。如果我们使用 “ typeof”运算符可获取未声明变量的值,我们将 面对运行时错误,返回值为“ undefined”。范围 未声明的变量始终是全局变量。
例如:
- 未定义:
var a;
undefined
console.log(a) // Success!
- 未声明:
console.log(myVariable) // ReferenceError: myVariable is not defined
当我们尝试记录undeclared
变量时,它将引发错误。尝试记录undefined
变量不会。我们制作一个try catch
来进行检查。
'use strict'
值得一提的是,在代码中添加'use strict'
会验证没有未声明的变量存在,并且如果存在未声明的变量,则会引发错误。
function define() {
//'use strict' verifies that no undeclared variable is present in our code
'use strict';
x = "Defined";
}
define();
ReferenceError: x is not defined
进一步阅读:
- Checking if a variable exists in javascript
- What are undeclared and undefined variables in JavaScript?
- JS Interview Question: What’s the difference between a variable that is: null,undefined or undeclared?
- JavaScript check if variable exists (is defined/initialized)
- Strict mode
正如其他人已经指出的那样,OP可能希望区分已声明但未定义的引用和未声明的引用名称...
let declaredButUnassignedAndStrictlyEqualToUndefinedValue;
const declaredAndHavingAssignedTheUndefinedValue = undefined;
// There is no way of telling the above two (un/)assignements appart.
console.log(
'(declaredButUnassignedAndStrictlyEqualToUndefinedValue === declaredAndHavingAssignedTheUndefinedValue) ?',(declaredButUnassignedAndStrictlyEqualToUndefinedValue === declaredAndHavingAssignedTheUndefinedValue)
);
// the `typeof` operator is of no help
// if it comes to distinguish between
// declared but undefined references
// and undeclared reference names ...
console.log(
'typeof notDeclaredWithinScope :',typeof notDeclaredWithinScope
);
// ... just a try catch can do that.
try {
notDeclaredWithinScope;
} catch (err) {
// console.log(err.message);
console.log('`notDeclaredWithinScope` does not exist within this scope.')
}
.as-console-wrapper { min-height: 100%!important; top: 0; }
,
我明白你在说什么。没有获得确切答案的定义方法,但是有一种方法可以确定是否定义了答案。只有在某处引用时才可能。
例如: //让我们以为x没有定义
x.substring(1);
输出: ReferenceError:“ x”未定义
因此,如果您使用try catch块方法,则在catch错误消息的帮助下,您可以确定它是否已定义!
,感谢所有帮助!我已经拼凑了一个简单的解决方案,如果有人需要,它可以满足所有答案中我的需求。唯一的缺点是变量名称必须作为字符串传递。它使用了try catch块,但我仍可以将其用于原始用例(根据其分配常量)。
function declared(variable) {
let declared = true;
try {
eval(variable);
} catch (e) {
if (e.name === "ReferenceError") {
declared = false;
}
}
return declared;
}
let declaredVar;
console.log(declared("declaredVar")); // true
console.log(declared("undeclaredVar")); // false
function typeOf(variable) {
return eval("typeof " + variable) === "undefined"
? declared(variable)
? "undefined"
: "undeclared"
: eval("typeof " + variable);
}
const stringVar = "string";
const undefinedVar = undefined;
console.log(typeOf("stringVar")); // string
console.log(typeOf("undefinedVar")); // undefined
console.log(typeOf("undeclaredVar")); // undeclared
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。