变量声明可以引用同一行中声明的其他变量吗?
我经常使用这种语法,但我不明白为什么它能有效。
var a = 1, b = a + 1;
console.log(b); // 2
如果您声明一个 var,在用逗号分隔它们之后,b
已经将 a
视为已评估?这是为什么?
I use this syntax often but I don't understand why it simply works.
var a = 1, b = a + 1;
console.log(b); // 2
In the event you're declaring a var, after splitting them on a comma, the b
already sees a
as evaluated? Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它已被定义。
一、基本术语的定义:
并且:
适用于您的问题的实际定义是这样的:
因此,在执行 #2 时,#1 已经被求值,您可以在 #2 中使用它的任何效果。
It has been defined as such.
First, the definition of the essential terms:
and:
The actual definition which applies to your question is this one:
So at the time #2 is executed, #1 has been evaluated already and you can use any effect of it in #2.
这是由 JavaScript 中变量的声明方式决定的。 Javascript 中的变量声明分两步进行。首先,当前作用域中声明的所有变量都被初始化并赋予值 undefined,在所有变量都以这种方式声明后,然后赋予它们实际值。所以你的代码:
被翻译为:
这称为提升。由于您声明的所有变量都被提升到作用域的顶部。这允许你做一些奇怪的事情,比如:
That's due to how variables are declared in JavaScript. Variable declaration in Javascript happens in two steps. First, the all the variables declared in the current scope are initialized and given the value undefined and after all the variables are declared this way, they are then given their actual value. So your code:
is translated to:
This is called hoisting. As all the variables you declare are hoisted at the top of the scope. This allows you to do weird things like:
很简单,因为 a 在 b 之前初始化。这个过程是从左到右进行的。
Simply because a gets initialized before b. This process goes from the left to the right.
这有点违反直觉,但只需将其视为与此相同:
与 Python 等其他语言不同,Python 中的多个赋值对先前的值进行操作(使交换更容易)
It's a bit counter-intuitive but just think of it as equal to this:
Unlike other languages like Python where multiple assignments operate on the previous values (making swaps easier)