为什么控制台中的变量声明总是返回“未定义”?
我使用的是最新的 Firefox (4.0.1) 和 Firebug (1.7.2)。
每当我在控制台中输入变量声明时,都会返回斜体“未定义”警告。
例如,如果我输入“var x = 5;”那么响应是“未定义”,而不是“5”。
之后,如果我在控制台中输入“x”,则会返回正确的值 5。然而,错误/警告有点麻烦,我真的很想知道原因和解决方案,以及我是否是唯一经历过这种情况的人。
有趣的是,如果我不使用“var”,而只是使用“x=5”声明值,则会显示正确的行为,并在控制台中返回“5”。
I am using the latest Firefox (4.0.1) and Firebug (1.7.2).
Any time I enter a variable declaration into the console, an italicized "undefined" warning is returned.
So for example if I enter "var x = 5;" then the response is "undefined", rather than "5".
Afterward if I enter "x" into the console, the proper value of 5 is returned. However the error/warning is a bit of a nuisance, would really like to know the cause and resolution, and if I'm the only one experiencing this.
Interestingly if I don't use "var" but just declare the value using "x=5" then the correct behavior exhibits and "5" is returned in the console.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(这只是一个猜测,我不是 Javascript 语言规则细节或 Firebug 的专家。)
控制台给您的反馈是您输入的行的评估结果。我假设声明
var x = ...
是一个没有值的语句,而简单的赋值 (x = ...
>) 符合 C 的传统和函数式语言的“一切都是表达式”态度,是一个计算指定值的表达式。(This is just a guess, I'm not an expert on the details of Javascript's language rules or on Firebug.)
The feedback the console gives you is the result of the evaluation of the line you entered. I assume the declaration
var x = ...
is a statement that doesn't have a value, while simple assignment (x = ...
) is, in line with the C heritage and the "everything is an expression" attitude of functional languages, an expression that evaluates to the assigned value.与其他一些语言不同,JavaScript 中的每段代码要么是表达式,要么是语句。
表达式总是返回一个值。语句始终返回未定义。什么是语句、什么是表达式在 1997 年的原始 JavaScript 规范。
例如,假设这是我们的程序:
您会注意到,如果您在控制台中逐行输入此内容,第一行返回未定义,而第二行返回“红色”。
这是因为,正如您可能已经猜到的那样,变量声明 (
var Something = Something
) 是一个语句,而变量赋值 (something = Something
) 是一个表达式。如果您好奇,请尝试阅读 11.13.1(第 50 页)中 JavaScript 如何评估分配,位于我上面链接的规范中的“简单分配”部分。
Unlike some other languages, in JavaScript every piece of code is either an expression or a statement.
Expressions always return a value. Statements always return undefined. What is a statement and what is an expression is defined in the original JavaScript specification from 1997.
For example, say this is our program:
You will notice that if you enter this line-by-line into your console, the 1st line returns undefined, while the 2nd line returns "red".
This is because, as you may have guessed, a variable declaration (
var something = something
) is a statement, whereas a variable assignment (something = something
) is an expression.If you're curious, try reading through how JavaScript evaluates an assignment in 11.13.1 (page 50), under the "Simple Assignment" section in the spec I linked above.
Firebug 报告计算表达式的结果,相当于:
typeof eval("var x = 5;");
“未定义”
typeof eval("x = 5;");
“数字”
Firebug is reporting the result of evaluating the expression, equivalent to:
typeof eval("var x = 5;");
"undefined"
typeof eval("x = 5;");
"number"