变量声明可以引用同一行中声明的其他变量吗?

发布于 2024-12-22 00:31:02 字数 177 浏览 3 评论 0原文

我经常使用这种语法,但我不明白为什么它能有效。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

起风了 2024-12-29 00:31:02

它已被定义

一、基本术语的定义:

变量语句

var VariableDeclarationList ;

并且:

变量声明列表

变量声明

变量声明列表变量声明

适用于您的问题的实际定义是这样的:

生产VariableDeclarationListVariableDeclarationListVariableDeclaration评估如下:

  1. 评估VariableDeclarationList。

  2. 评估VariableDeclaration。

因此,在执行 #2 时,#1 已经被求值,您可以在 #2 中使用它的任何效果。

It has been defined as such.

First, the definition of the essential terms:

VariableStatement :

var VariableDeclarationList ;

and:

VariableDeclarationList :

VariableDeclaration

VariableDeclarationList , VariableDeclaration

The actual definition which applies to your question is this one:

The production VariableDeclarationList : VariableDeclarationList , VariableDeclaration is evaluated as follows:

  1. Evaluate VariableDeclarationList.

  2. Evaluate VariableDeclaration.

So at the time #2 is executed, #1 has been evaluated already and you can use any effect of it in #2.

黎歌 2024-12-29 00:31:02

这是由 JavaScript 中变量的声明方式决定的。 Javascript 中的变量声明分两步进行。首先,当前作用域中声明的所有变量都被初始化并赋予值 undefined,在所有变量都以这种方式声明后,然后赋予它们实际值。所以你的代码:

var a = 1, b = a + 1;

被翻译为:

var a = undefined;
var b = undefined;
a = 1;
b = a + 1;

这称为提升。由于您声明的所有变量都被提升到作用域的顶部。这允许你做一些奇怪的事情,比如:

var a = b;  // b = undefined
var b = 0;

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:

var a = 1, b = a + 1;

is translated to:

var a = undefined;
var b = undefined;
a = 1;
b = a + 1;

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:

var a = b;  // b = undefined
var b = 0;
差↓一点笑了 2024-12-29 00:31:02

很简单,因为 a 在 b 之前初始化。这个过程是从左到右进行的。

Simply because a gets initialized before b. This process goes from the left to the right.

把昨日还给我 2024-12-29 00:31:02

这有点违反直觉,但只需将其视为与此相同:

var a = 1;
var b = a + 1;

与 Python 等其他语言不同,Python 中的多个赋值对先前的值进行操作(使交换更容易)

It's a bit counter-intuitive but just think of it as equal to this:

var a = 1;
var b = a + 1;

Unlike other languages like Python where multiple assignments operate on the previous values (making swaps easier)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文