If you attempt to use a variable that does not exist and has not been declared, javascript will throw an error. var name is not defined
, and the script will stop then and there.
如果您尝试使用不存在且尚未声明的变量,则javascript将引发错误。 var name未定义,脚本将在那里停止。
But if you check it using typeof noname
then it will return "undefined"
. I always thought that you had to declare a var for it to have a type. Either by using: var a; so it has the type of undefined or by giving it a value like: var b =5;
so it has the type of its value.
但是如果你使用typeof noname检查它,那么它将返回“undefined”。我一直认为你必须声明一个var才能拥有一个类型。通过使用:var a;因此它具有未定义的类型或赋予它类似的值:var b = 5;所以它有它的价值类型。
Also what is the difference between var a;
and var b = undefined;
?
var a之间有什么区别;和var b =未定义;?
7 个解决方案
#1
22
An undeclared variable (that is, one that doesn't exist) does not have a type - and so its type is undefined. I believe that the generally accepted way to test if something is undefined is
未声明的变量(即,不存在的变量)没有类型 - 因此其类型未定义。我相信普遍接受的测试方法是否未定义的方法是
typeof var === 'undefined'
rather than
var === undefined
since if the variable does not exist, you cannot access it. The latter case might be more useful if you are sure the variable should exist, since the difference between the two is that an undeclared variable will return false in the first case but cause an error in the second case.
因为如果变量不存在,则无法访问它。如果您确定变量应该存在,后一种情况可能会更有用,因为两者之间的差异是未声明的变量在第一种情况下将返回false但在第二种情况下会导致错误。
Make sure that you use the triple-equals operator though if you're using the second variant; the (more usual) double-equals operator performs type coercion, so null == undefined
is true while null === undefined
is false. Sometimes you might want the first behaviour, though often you'll want the second, especially if you're testing against undefined, so it's important to recognise the difference. (This is another benefit of the first case since it's not possible to make this subtle error).
如果您使用的是第二种变体,请确保使用三等号运算符; (更常见的)double-equals运算符执行类型强制,因此null == undefined为true,而null === undefined为false。有时您可能想要第一个行为,但通常您会想要第二个行为,特别是如果您正在测试未定义的行为,因此识别差异非常重要。 (这是第一种情况的另一个好处,因为它不可能产生这种微妙的错误)。
Yes, variables can have a value of undefined and you can explicitly assign values to them. Assigning undefined
to a variable though is probably confusing, since it's a bit of a paradox (you've defined the variable as undefined) and it's not possible to distinguish that variable from either variables that don't exist or uninitialised variables. Use null if you want to signify that a variable has no value currently, or if you want to "undeclare" the variable altogether, use delete {varname}
. Assigning undefined to a variable does not remove that variable's declaration; and it will still appear in the list of its owning object's properties if you iterate over them, so I can't think of any situation this would benefit you.
是的,变量的值可以是undefined,您可以显式为它们赋值。虽然将undefined分配给变量可能会令人困惑,因为它有点悖论(您已将变量定义为未定义)并且无法将该变量与不存在的变量或未初始化的变量区分开来。如果要表示变量当前没有值,或者如果要完全“取消声明”变量,请使用null,使用delete {varname}。将undefined赋值给变量不会删除该变量的声明;如果你迭代它们,它仍然会出现在它拥有对象的属性列表中,所以我想不出任何会对你有益的情况。
Edit: In response to the comment, when comparing the values with === (or ==), the variable must be deferenced to obtain its current value in order to do the comparison. Since the variable doesn't exist, this dereferencing fails (no real surprises so far). While you might expect the typeof operator to work in a similar way (get the current value, see what its type is) it specifically works with undefined variables. The "short version" (as used by the Mozilla reference ) is simply that "The typeof operator returns a string indicating the type of the unevaluated operand."
编辑:在响应注释时,在将值与===(或==)进行比较时,必须引用变量以获取其当前值以进行比较。由于该变量不存在,因此该解除引用失败(到目前为止没有真正的意外)。虽然您可能希望typeof运算符以类似的方式工作(获取当前值,查看其类型),但它特别适用于未定义的变量。 “短版本”(由Mozilla引用使用)只是“typeof运算符返回一个字符串,指示未评估的操作数的类型。”
The long version, extracted from the ECMAScript spec, is that there's a special case for undefined variables:
从ECMAScript规范中提取的长版本是未定义变量的特殊情况:
11.4.3 typeof UnaryExpression is evaluated as follows:
11.4.3 typeof UnaryExpression的计算方法如下:
- Evaluate UnaryExpression (as per 10.1.4 this returns "a value of type Reference whose base object is null and whose property name is the identifier" if the variable is undeclared).
评估UnaryExpression(根据10.1.4,它返回“类型为Reference的值,其基础对象为null,如果变量未声明,则其属性名称为标识符”)。
- If Type(Result(1)) is not Reference, go to step 4. (It is a Reference)
如果Type(Result(1))不是Reference,请转到步骤4.(这是参考)
- If GetBase(Result(1)) is null, return "undefined". (This is the special case matching undefined variables)
如果GetBase(Result(1))为null,则返回“undefined”。 (这是匹配未定义变量的特殊情况)
As for your comment to the first question, "how can you classify what does not exist" - it's easy! Simply divide all concepts into things that do exist (e.g. squirrel, rock) and those that don't exist (unicorns, warp drives). That's what undefined means; regardless of its semantics in English, its Javascript meaning is that the variable hasn't been declared or populated yet, and so while the concept of "a variable called foo" is valid, there exists no variable with that name holding a real value.
至于你对第一个问题的评论,“你怎么能分类不存在的东西” - 这很简单!简单地将所有概念划分为存在的东西(例如松鼠,岩石)和不存在的东西(独角兽,翘曲驱动器)。这就是未定义的意思;不管它的英文语义如何,它的Javascript含义是该变量尚未被声明或填充,因此虽然“一个名为foo的变量”的概念是有效的,但是不存在具有该实名值的变量。
#2
13
JavaScript provides several different notions of missing or empty variables (and object properties):
JavaScript提供了几种不同的缺失或空变量(和对象属性)概念:
-
Variables that are actually 'not defined', i.e. they don't exists as a given name isn't bound in the current lexical environment. Accessing such a variable will throw an error, but using
typeof
won't and will return'undefined'
. In contrast, accessing non-existing properties will not throw an error and returnundefined
instead (and you may use thein
operator or thehasOwnProperty()
method to check if properties actually do exist).实际上“未定义”的变量,即它们不作为给定名称存在,不受当前词法环境的约束。访问这样的变量会引发错误,但使用typeof将不会返回'undefined'。相反,访问不存在的属性不会抛出错误并返回undefined(并且您可以使用in运算符或hasOwnProperty()方法来检查属性是否确实存在)。
-
Existing variables which have not been assigned a value (which is common because of var hoisting) or which have been explicitly set to
undefined
. Accessing such a variable will returnundefined
,typeof
will return'undefined'
.未分配值的现有变量(由于var提升而常见)或已明确设置为未定义的现有变量。访问这样的变量将返回undefined,typeof将返回'undefined'。
-
Existing variables which have been explicitly set to
null
. Accessing such a variable will returnnull
,typeof
will return'object'
. Note that this is misleading:null
is not an object, but a primitive value of type Null (which has the consequence that you can't returnnull
from constructor functions - you have to throw an error instead to denote failure).已显式设置为null的现有变量。访问这样的变量将返回null,typeof将返回'object'。请注意,这是误导:null不是对象,而是Null类型的原始值(其结果是您不能从构造函数返回null - 您必须抛出错误来表示失败)。
I'd recommend the following practices:
我推荐以下做法:
- Use
typeof
to check forundefined
, as it will cover the first two cases. - Don't assign
undefined
to properties: Usedelete
to get rid of them instead; note that you cannot delete variables (but also note that globals are actually properties of the global object and thus can be deleted). - Use
null
to mark the absence of a meaningful value (eg the forward reference of the last node of a linked list) or if you want to clear a variable as a hint to the garbage collector.
使用typeof检查undefined,因为它将涵盖前两种情况。
不要将undefined赋值给属性:使用delete来取消它们;请注意,您无法删除变量(但请注意,全局变量实际上是全局对象的属性,因此可以删除)。
使用null标记缺少有意义的值(例如,链接列表的最后一个节点的前向引用),或者如果要将变量清除为垃圾收集器的提示。
You could go with undefined
for 3. as well and never use null
at all.
您也可以使用undefined for 3.并且根本不使用null。
#3
3
I believe it's a difference between JavaScript definition and firebugs of the same thing.
我相信这是同一件事的JavaScript定义和firebugs之间的区别。
Undefined is just the state of something that has not been defined as a value. So it has no type.
未定义只是未定义为值的某种状态。所以它没有类型。
Also what is the difference between var a; and var b = undefined;
var a之间有什么区别;和var b =未定义;
var a; alert(a); // undefined
a; alert(a); // "Error "a" not defined"
a = undefined; alert(a); // undefined
2nd example is not valid JavaScript code and the execution will stop. Since this is an error.
第二个示例是无效的JavaScript代码,执行将停止。由于这是一个错误。
#4
2
alert(a);
Here a
is not defined.
这里没有定义。
alert(a);
var a=10;
Here a
is undefined .becacuse javascript engine convert this code to
这里有一个未定义的.becacuse javascript引擎将此代码转换为
var a;
alert(a); // that's why `a` is defined here
a=10;
#5
0
An undeclared variable does not exist in Javascript memory whereas a declared one does and can be set to undefined.
Javascript内存中不存在未声明的变量,而声明的变量可以设置为未定义。
The difference is caused by Javascript design confusion. If a variable's value is undefined then it should be deleted. Indeed falsy values like 0, "", null, and undefined, are all basically meaningless and identical. A lot of time is wasted on them. They are all nothing and non existent. It is highly contradictory to have more than one type of nothing, or maybe to allow even one.
差异是由Javascript设计混淆引起的。如果变量的值未定义,则应删除它。实际上,像0,“”,null和undefined这样的虚假值基本上都是无意义和相同的。浪费了很多时间。它们都没有,也不存在。拥有多种类型的东西,或者甚至允许一种类型,这是非常矛盾的。
Therefore I think you should avoid explicitly using falsy values when programming altogether. I didn't find a case yet when they couldn't be eliminated by a better method, and programming is much nicer without them.
因此,我认为你应该避免在完全编程时明确使用伪值。当他们无法通过更好的方法消除时,我还没有找到一个案例,如果没有它们,编程会更好。
#6
0
undefined: Declared but the value not asigned above where we access it in othe word it exist but the value not asigned
undefined:声明但是上面的值没有在我们访问它的地方,但它存在但是没有符号的值
'not defined': It is an error which indicate to the coder/programmer/user the variable doesn't exist in the scope. Not declare in scope.
'not defined':这是一个错误,它向编码器/程序员/用户指示该范围内不存在该变量。不在范围内声明。
var a = 1;
console.log(a) //1
var b;
console.log(b) //undefined
console.log(c) //undefined
var c=2;
console.log(d) //undefined
var d;
e=3
console.log(e) //3
var e;
console.log(f) //Uncaught ReferenceError: f is not defined
> Note: the default behavior of javaScript moving declarations to the > top >So the above code is look like below internally
var a = 1, b, c, d, e;
console.log(a) //1
console.log(b) //undefined
console.log(c) //undefined
c=2;
console.log(d) //undefined
e=3
console.log(e) //3
console.log(f) //Uncaught ReferenceError: f is not defined
#7
0
Not defined:
Variable is not declared or initialized. Throws reference error
变量未声明或初始化。引发参考错误
Example:
console.log(newvariable); // results: ReferenceError: newvariable is not defined
Undefined:
A variable declared without a value will have the value undefined.
声明没有值的变量将具有undefined值。
Example:
var newVar;
console.log(newVar); // results: undefined
#1
22
An undeclared variable (that is, one that doesn't exist) does not have a type - and so its type is undefined. I believe that the generally accepted way to test if something is undefined is
未声明的变量(即,不存在的变量)没有类型 - 因此其类型未定义。我相信普遍接受的测试方法是否未定义的方法是
typeof var === 'undefined'
rather than
var === undefined
since if the variable does not exist, you cannot access it. The latter case might be more useful if you are sure the variable should exist, since the difference between the two is that an undeclared variable will return false in the first case but cause an error in the second case.
因为如果变量不存在,则无法访问它。如果您确定变量应该存在,后一种情况可能会更有用,因为两者之间的差异是未声明的变量在第一种情况下将返回false但在第二种情况下会导致错误。
Make sure that you use the triple-equals operator though if you're using the second variant; the (more usual) double-equals operator performs type coercion, so null == undefined
is true while null === undefined
is false. Sometimes you might want the first behaviour, though often you'll want the second, especially if you're testing against undefined, so it's important to recognise the difference. (This is another benefit of the first case since it's not possible to make this subtle error).
如果您使用的是第二种变体,请确保使用三等号运算符; (更常见的)double-equals运算符执行类型强制,因此null == undefined为true,而null === undefined为false。有时您可能想要第一个行为,但通常您会想要第二个行为,特别是如果您正在测试未定义的行为,因此识别差异非常重要。 (这是第一种情况的另一个好处,因为它不可能产生这种微妙的错误)。
Yes, variables can have a value of undefined and you can explicitly assign values to them. Assigning undefined
to a variable though is probably confusing, since it's a bit of a paradox (you've defined the variable as undefined) and it's not possible to distinguish that variable from either variables that don't exist or uninitialised variables. Use null if you want to signify that a variable has no value currently, or if you want to "undeclare" the variable altogether, use delete {varname}
. Assigning undefined to a variable does not remove that variable's declaration; and it will still appear in the list of its owning object's properties if you iterate over them, so I can't think of any situation this would benefit you.
是的,变量的值可以是undefined,您可以显式为它们赋值。虽然将undefined分配给变量可能会令人困惑,因为它有点悖论(您已将变量定义为未定义)并且无法将该变量与不存在的变量或未初始化的变量区分开来。如果要表示变量当前没有值,或者如果要完全“取消声明”变量,请使用null,使用delete {varname}。将undefined赋值给变量不会删除该变量的声明;如果你迭代它们,它仍然会出现在它拥有对象的属性列表中,所以我想不出任何会对你有益的情况。
Edit: In response to the comment, when comparing the values with === (or ==), the variable must be deferenced to obtain its current value in order to do the comparison. Since the variable doesn't exist, this dereferencing fails (no real surprises so far). While you might expect the typeof operator to work in a similar way (get the current value, see what its type is) it specifically works with undefined variables. The "short version" (as used by the Mozilla reference ) is simply that "The typeof operator returns a string indicating the type of the unevaluated operand."
编辑:在响应注释时,在将值与===(或==)进行比较时,必须引用变量以获取其当前值以进行比较。由于该变量不存在,因此该解除引用失败(到目前为止没有真正的意外)。虽然您可能希望typeof运算符以类似的方式工作(获取当前值,查看其类型),但它特别适用于未定义的变量。 “短版本”(由Mozilla引用使用)只是“typeof运算符返回一个字符串,指示未评估的操作数的类型。”
The long version, extracted from the ECMAScript spec, is that there's a special case for undefined variables:
从ECMAScript规范中提取的长版本是未定义变量的特殊情况:
11.4.3 typeof UnaryExpression is evaluated as follows:
11.4.3 typeof UnaryExpression的计算方法如下:
- Evaluate UnaryExpression (as per 10.1.4 this returns "a value of type Reference whose base object is null and whose property name is the identifier" if the variable is undeclared).
评估UnaryExpression(根据10.1.4,它返回“类型为Reference的值,其基础对象为null,如果变量未声明,则其属性名称为标识符”)。
- If Type(Result(1)) is not Reference, go to step 4. (It is a Reference)
如果Type(Result(1))不是Reference,请转到步骤4.(这是参考)
- If GetBase(Result(1)) is null, return "undefined". (This is the special case matching undefined variables)
如果GetBase(Result(1))为null,则返回“undefined”。 (这是匹配未定义变量的特殊情况)
As for your comment to the first question, "how can you classify what does not exist" - it's easy! Simply divide all concepts into things that do exist (e.g. squirrel, rock) and those that don't exist (unicorns, warp drives). That's what undefined means; regardless of its semantics in English, its Javascript meaning is that the variable hasn't been declared or populated yet, and so while the concept of "a variable called foo" is valid, there exists no variable with that name holding a real value.
至于你对第一个问题的评论,“你怎么能分类不存在的东西” - 这很简单!简单地将所有概念划分为存在的东西(例如松鼠,岩石)和不存在的东西(独角兽,翘曲驱动器)。这就是未定义的意思;不管它的英文语义如何,它的Javascript含义是该变量尚未被声明或填充,因此虽然“一个名为foo的变量”的概念是有效的,但是不存在具有该实名值的变量。
#2
13
JavaScript provides several different notions of missing or empty variables (and object properties):
JavaScript提供了几种不同的缺失或空变量(和对象属性)概念:
-
Variables that are actually 'not defined', i.e. they don't exists as a given name isn't bound in the current lexical environment. Accessing such a variable will throw an error, but using
typeof
won't and will return'undefined'
. In contrast, accessing non-existing properties will not throw an error and returnundefined
instead (and you may use thein
operator or thehasOwnProperty()
method to check if properties actually do exist).实际上“未定义”的变量,即它们不作为给定名称存在,不受当前词法环境的约束。访问这样的变量会引发错误,但使用typeof将不会返回'undefined'。相反,访问不存在的属性不会抛出错误并返回undefined(并且您可以使用in运算符或hasOwnProperty()方法来检查属性是否确实存在)。
-
Existing variables which have not been assigned a value (which is common because of var hoisting) or which have been explicitly set to
undefined
. Accessing such a variable will returnundefined
,typeof
will return'undefined'
.未分配值的现有变量(由于var提升而常见)或已明确设置为未定义的现有变量。访问这样的变量将返回undefined,typeof将返回'undefined'。
-
Existing variables which have been explicitly set to
null
. Accessing such a variable will returnnull
,typeof
will return'object'
. Note that this is misleading:null
is not an object, but a primitive value of type Null (which has the consequence that you can't returnnull
from constructor functions - you have to throw an error instead to denote failure).已显式设置为null的现有变量。访问这样的变量将返回null,typeof将返回'object'。请注意,这是误导:null不是对象,而是Null类型的原始值(其结果是您不能从构造函数返回null - 您必须抛出错误来表示失败)。
I'd recommend the following practices:
我推荐以下做法:
- Use
typeof
to check forundefined
, as it will cover the first two cases. - Don't assign
undefined
to properties: Usedelete
to get rid of them instead; note that you cannot delete variables (but also note that globals are actually properties of the global object and thus can be deleted). - Use
null
to mark the absence of a meaningful value (eg the forward reference of the last node of a linked list) or if you want to clear a variable as a hint to the garbage collector.
使用typeof检查undefined,因为它将涵盖前两种情况。
不要将undefined赋值给属性:使用delete来取消它们;请注意,您无法删除变量(但请注意,全局变量实际上是全局对象的属性,因此可以删除)。
使用null标记缺少有意义的值(例如,链接列表的最后一个节点的前向引用),或者如果要将变量清除为垃圾收集器的提示。
You could go with undefined
for 3. as well and never use null
at all.
您也可以使用undefined for 3.并且根本不使用null。
#3
3
I believe it's a difference between JavaScript definition and firebugs of the same thing.
我相信这是同一件事的JavaScript定义和firebugs之间的区别。
Undefined is just the state of something that has not been defined as a value. So it has no type.
未定义只是未定义为值的某种状态。所以它没有类型。
Also what is the difference between var a; and var b = undefined;
var a之间有什么区别;和var b =未定义;
var a; alert(a); // undefined
a; alert(a); // "Error "a" not defined"
a = undefined; alert(a); // undefined
2nd example is not valid JavaScript code and the execution will stop. Since this is an error.
第二个示例是无效的JavaScript代码,执行将停止。由于这是一个错误。
#4
2
alert(a);
Here a
is not defined.
这里没有定义。
alert(a);
var a=10;
Here a
is undefined .becacuse javascript engine convert this code to
这里有一个未定义的.becacuse javascript引擎将此代码转换为
var a;
alert(a); // that's why `a` is defined here
a=10;
#5
0
An undeclared variable does not exist in Javascript memory whereas a declared one does and can be set to undefined.
Javascript内存中不存在未声明的变量,而声明的变量可以设置为未定义。
The difference is caused by Javascript design confusion. If a variable's value is undefined then it should be deleted. Indeed falsy values like 0, "", null, and undefined, are all basically meaningless and identical. A lot of time is wasted on them. They are all nothing and non existent. It is highly contradictory to have more than one type of nothing, or maybe to allow even one.
差异是由Javascript设计混淆引起的。如果变量的值未定义,则应删除它。实际上,像0,“”,null和undefined这样的虚假值基本上都是无意义和相同的。浪费了很多时间。它们都没有,也不存在。拥有多种类型的东西,或者甚至允许一种类型,这是非常矛盾的。
Therefore I think you should avoid explicitly using falsy values when programming altogether. I didn't find a case yet when they couldn't be eliminated by a better method, and programming is much nicer without them.
因此,我认为你应该避免在完全编程时明确使用伪值。当他们无法通过更好的方法消除时,我还没有找到一个案例,如果没有它们,编程会更好。
#6
0
undefined: Declared but the value not asigned above where we access it in othe word it exist but the value not asigned
undefined:声明但是上面的值没有在我们访问它的地方,但它存在但是没有符号的值
'not defined': It is an error which indicate to the coder/programmer/user the variable doesn't exist in the scope. Not declare in scope.
'not defined':这是一个错误,它向编码器/程序员/用户指示该范围内不存在该变量。不在范围内声明。
var a = 1;
console.log(a) //1
var b;
console.log(b) //undefined
console.log(c) //undefined
var c=2;
console.log(d) //undefined
var d;
e=3
console.log(e) //3
var e;
console.log(f) //Uncaught ReferenceError: f is not defined
> Note: the default behavior of javaScript moving declarations to the > top >So the above code is look like below internally
var a = 1, b, c, d, e;
console.log(a) //1
console.log(b) //undefined
console.log(c) //undefined
c=2;
console.log(d) //undefined
e=3
console.log(e) //3
console.log(f) //Uncaught ReferenceError: f is not defined
#7
0
Not defined:
Variable is not declared or initialized. Throws reference error
变量未声明或初始化。引发参考错误
Example:
console.log(newvariable); // results: ReferenceError: newvariable is not defined
Undefined:
A variable declared without a value will have the value undefined.
声明没有值的变量将具有undefined值。
Example:
var newVar;
console.log(newVar); // results: undefined