我想检查变量是否已定义。例如,以下抛出未定义的错误
alert( x );
我怎样才能捕捉到这个错误?
在 JavaScript 中,null
是一个对象。不存在的事物还有另一个价值,undefined
. DOMnull
在几乎所有无法在文档中找到某些结构的情况下都会返回,但在 JavaScript 本身undefined
中就是使用的值。
其次,不,没有直接的等价物。如果您真的想专门检查null
,请执行以下操作:
if (yourvar === null) // Does not execute if yourvar is `undefined`
如果要检查变量是否存在,只能使用try
/来完成catch
,因为typeof
会将未声明的变量和使用值声明的变量undefined
视为等效的。
但是,要检查变量是否已声明且未undefined
声明:
if (yourvar !== undefined) // Any scope
以前,必须使用typeof
运算符安全地检查 undefined,因为可以undefined
像变量一样重新分配。旧方式如下所示:
if (typeof yourvar !== 'undefined') // Any scope
undefined
可重新分配的问题已在 2009 年发布的 ECMAScript 5 中得到修复。您现在可以安全地使用===
和!==
测试,undefined
而无需使用一段typeof
时间undefined
以来一直是只读的。
如果你想知道一个成员是否独立存在但不关心它的值是什么:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
如果您想知道变量是否为真:
if (yourvar)
真正测试变量是否undefined
是的唯一方法是执行以下操作。请记住,未定义是 JavaScript 中的一个对象。
if (typeof someVar === 'undefined') {
// Your variable is undefined
}
这个线程中的一些其他解决方案会让你相信一个变量是未定义的,即使它已经定义(例如,值为 NULL 或 0)。
从技术上讲,正确的解决方案是(我相信):
typeof x === "undefined"
你有时会变得懒惰并使用
x == null
但这允许未定义的变量 x 和包含 null 的变量 x 返回 true。
一个更简单、更简写的版本是:
if (!x) {
//Undefined
}
或者
if (typeof x !== "undefined") {
//Do something since x is defined.
}
我经常这样做:
function doSomething(variable)
{
var undef;
if(variable === undef)
{
alert('Hey moron, define this bad boy.');
}
}
void
运算符返回undefined
传递给它的任何参数/表达式。因此您可以针对结果进行测试(实际上一些缩小器将您的代码从 更改undefined
为void 0
以保存几个字符)
例如:
void 0
// undefined
if (variable === void 0) {
// variable is undefined
}
该错误告诉您x
甚至不存在!它还没有被声明,这与被赋值不同。
var x; // declaration
x = 2; // assignment
如果您声明x
,您将不会收到错误消息。您会收到一条警报,说明undefined
因为x
存在/已声明但尚未分配值。
要检查变量是否已声明,您可以使用typeof
,任何其他检查变量是否存在的方法都会引发您最初遇到的相同错误。
if(typeof x !== "undefined") {
alert(x);
}
这是检查存储在 中的值的类型x
。它只会undefined
在x
尚未声明或已声明但尚未分配时返回。
另一个潜在的“解决方案”是使用window
对象。它避免了在浏览器中的引用错误问题。
if (window.x) {
alert('x exists and is truthy');
} else {
alert('x does not exist, or exists and is falsy');
}
很抱歉死灵,但这里的大多数答案都混淆了“未定义”和“未定义”
未定义- 声明了一个变量,但它的值未定义。
未定义- 甚至没有声明变量。
检查这两种情况的唯一安全方法是使用typeof myVar === 'undefined'
myVar === undefined
只会检查案例编号 (1)。myVar
如果甚至没有声明,它仍然会为案例编号 (2) 抛出“myVar is not defined” 。OP专门询问“甚至没有定义”的情况(2)。
PS 我确实理解“案例 2”在现代 ES6 世界中变得越来越少,但一些旧的遗留组件仍然存在于过去。
我经常使用最简单的方法:
var variable;
if (variable === undefined){
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
编辑:
不初始化变量,会抛出异常“Uncaught ReferenceError: variable is not defined...”
您还可以使用三元条件运算符:
var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
接受的答案是正确的。只是想再添加一个选项。您也可以使用try ... catch
块来处理这种情况。一个怪异的例子:
var a;
try {
a = b + 1; // throws ReferenceError if b is not defined
}
catch (e) {
a = 1; // apply some default behavior in case of error
}
finally {
a = a || 0; // normalize the result in any case
}
请注意catch
块,这有点混乱,因为它创建了块级范围。而且,当然,该示例非常简化以回答所提出的问题,它不包括错误处理的最佳实践;)。
只需执行以下操作:
function isNotDefined(value) {
return typeof value === "undefined";
}
并称之为:
isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false
我们可以检查undefined
如下
var x;
if (x === undefined) {
alert("x is undefined");
} else {
alert("x is defined");
}
我使用一个小函数来验证变量是否已被声明,这确实减少了我的 javascript 文件中的杂乱程度。我添加了对该值的检查,以确保该变量不仅存在,而且还被分配了一个值。第二个条件检查变量是否也已实例化,因为如果变量已定义但未实例化(参见下面的示例),如果您尝试在代码中引用它的值,它仍然会抛出错误。
未实例化 -var my_variable;
已实例化 -var my_variable = "";
function varExists(el) {
if ( typeof el !== "undefined" && typeof el.val() !== "undefined" ) {
return true;
} else {
return false;
}
}
然后,您可以使用条件语句来测试变量是否已像这样定义和实例化......
if ( varExists(variable_name) ) { // checks that it DOES exist }
或者测试它没有被定义和实例化使用......
if( !varExists(variable_name) ) { // checks that it DOESN'T exist }