如何检查一个变量是未定义还是未在 javascript 中声明?
How to check if a variable is undefined versus it is undeclared in javascript?
我知道要查找 javascript 中是否未声明变量,我可以使用 if (typeof variable === 'undefined')
。如果我将变量声明为未定义 (var variable = undefined
),则 if 语句仍然 returns 为真。是否可以在JavaScript中找到未声明的变量和值为未定义的变量之间的区别?我知道它们很相似,但是做 const variable = undefined
然后 variable = "something else"
会抛出错误,所以它们一定是不同的。
const variable = undefined
if (typeof variable === 'undefined') {
console.log('"variable" is undefined')
}
if (typeof undeclaredVariable === 'undefined') {
console.log('"undeclaredVariable" is undefined')
}
我不想使用 try catch 块,因为我希望能够基于此分配另一个常量。我想要这样的解决方案:const isVariableDeclared = variable === undeclared
,除了 javascript 中不存在 undeclared
。我知道我可以将 let 与 try catch 块一起使用,但我正在寻找更优雅的东西。
我明白你说的。没有确定的方法来获得确切的答案,但有一种方法可以确定它是否已定义。只有当它在某处引用时才有可能。
例如:
// 假设 x 未定义
x.substring(1);
输出:
ReferenceError:“x”未定义
所以如果你使用try catch块方法,借助catch错误信息你可以判断它是否被定义!
正如其他人已经指出的那样,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; }
至少在撰写本文时...不,您似乎不能这样做:
var a = undeclared(var) ? 'undeclared' : 'undefined'
原因是您不能将未声明的变量传递给函数;它会引发错误,即使在 non-strict 模式下也是如此。
我们能做的最好的是:
var barIsDeclared = true;
try { bar; }
catch (e) {
if (e.name == "ReferenceError") {
barIsDeclared = false;
}
}
console.log(barIsDeclared);
为什么?
Undefined: It occurs when a variable has been declared but has not
been assigned with any value. Undefined is not a keyword.
Undeclared: It occurs when we try to access any variable that is not
initialized or declared earlier using var or const keyword. If we use
‘typeof’ operator to get the value of an undeclared variable, we will
face the runtime error with return value as “undefined”. The scope of
the undeclared variables is always global.
例如:
- 未定义:
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
感谢大家的帮助!如果有人需要,我已经从所有答案中拼凑出一个适合我需求的简单解决方案。唯一的缺点是变量名必须作为字符串传递。它使用了一个 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
我知道要查找 javascript 中是否未声明变量,我可以使用 if (typeof variable === 'undefined')
。如果我将变量声明为未定义 (var variable = undefined
),则 if 语句仍然 returns 为真。是否可以在JavaScript中找到未声明的变量和值为未定义的变量之间的区别?我知道它们很相似,但是做 const variable = undefined
然后 variable = "something else"
会抛出错误,所以它们一定是不同的。
const variable = undefined
if (typeof variable === 'undefined') {
console.log('"variable" is undefined')
}
if (typeof undeclaredVariable === 'undefined') {
console.log('"undeclaredVariable" is undefined')
}
我不想使用 try catch 块,因为我希望能够基于此分配另一个常量。我想要这样的解决方案:const isVariableDeclared = variable === undeclared
,除了 javascript 中不存在 undeclared
。我知道我可以将 let 与 try catch 块一起使用,但我正在寻找更优雅的东西。
我明白你说的。没有确定的方法来获得确切的答案,但有一种方法可以确定它是否已定义。只有当它在某处引用时才有可能。
例如: // 假设 x 未定义
x.substring(1);
输出: ReferenceError:“x”未定义
所以如果你使用try catch块方法,借助catch错误信息你可以判断它是否被定义!
正如其他人已经指出的那样,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; }
至少在撰写本文时...不,您似乎不能这样做:
var a = undeclared(var) ? 'undeclared' : 'undefined'
原因是您不能将未声明的变量传递给函数;它会引发错误,即使在 non-strict 模式下也是如此。
我们能做的最好的是:
var barIsDeclared = true;
try { bar; }
catch (e) {
if (e.name == "ReferenceError") {
barIsDeclared = false;
}
}
console.log(barIsDeclared);
为什么?
Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.
Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global.
例如:
- 未定义:
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
感谢大家的帮助!如果有人需要,我已经从所有答案中拼凑出一个适合我需求的简单解决方案。唯一的缺点是变量名必须作为字符串传递。它使用了一个 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