如何检查变量是未定义还是未在 javascript 中声明?

Nat*_*Chu 8 javascript undefined detection undeclared-identifier

我知道要查找 javascript 中是否未声明变量,我可以使用if (typeof variable === 'undefined'). 如果我将变量声明为 undefined ( var variable = undefined),则 if 语句仍返回 true。在 JavaScript 中,是否有可能找到未声明的变量和值为 undefined 的变量之间的区别?我知道它们很相似,但是这样做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')
}
Run Code Online (Sandbox Code Playgroud)

我不想使用 try catch 块,因为我希望能够基于此分配另一个常量。我想要一个这样的解决方案:const isVariableDeclared = variable === undeclared,除非undeclared在 javascript 中不存在。我知道我可以将 let 与 try catch 块一起使用,但我正在寻找更优雅的东西。

bar*_*sor 2

至少在撰写本文时......不,您似乎不能做这样的事情:

\n
var a = undeclared(var) ? \'undeclared\' : \'undefined\'\n
Run Code Online (Sandbox Code Playgroud)\n

原因是你不能将未声明的变量传递给函数;即使在非严格模式下,它也会引发错误。

\n

我们能做的最好的就是:

\n

\r\n
\r\n
var a = undeclared(var) ? \'undeclared\' : \'undefined\'\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

为什么?

\n
\n

未定义:当变量已声明但尚未分配任何值时,就会发生这种情况。未定义不是关键字。

\n

未声明:当我们尝试访问任何未初始化或之前使用 var 或 const 关键字声明的变量时,就会发生这种情况。如果我们使用 \n\xe2\x80\x98typeof\xe2\x80\x99 运算符来获取未声明变量的值,\n我们将面临返回值为 \xe2\x80\x9cundefined\xe2\x80\x9d 的运行时错误。未声明变量的作用域始终是全局的。

\n
\n

例如:

\n
    \n
  • 不明确的:
  • \n
\n
var a;\nundefined\nconsole.log(a) // Success!\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 未申报:
  • \n
\n
console.log(myVariable) // ReferenceError: myVariable is not defined\n
Run Code Online (Sandbox Code Playgroud)\n

当我们尝试记录undeclared变量时,它会引发错误。尝试记录undefined变量却不会。我们做了一个try catch检查来检查这一点。

\n

\'use strict\'

\n

值得一提的是,\'use strict\'在代码中添加可验证是否存在未声明的变量,如果存在则引发错误。

\n
function define() {\n //\'use strict\' verifies that no undeclared variable is present in our code     \n \'use strict\';     \n x = "Defined";  \n}\n\ndefine();\n\nReferenceError: x is not defined\n
Run Code Online (Sandbox Code Playgroud)\n

进一步阅读:

\n\n