javascript - 奇怪但有效的 var 声明语法

标签 javascript

我经常使用这种语法,但我不明白它为何如此有效。

var a = 1, b = a + 1;
console.log(b); // 2

如果您要声明一个 var,在用逗号分隔它们之后,b 已经看到 a 被评估了?这是为什么?

最佳答案

已经defined因此。

一、基本术语的定义:

VariableStatement :

var VariableDeclarationList ;

和:

VariableDeclarationList :

VariableDeclaration

VariableDeclarationList , VariableDeclaration

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

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

  1. Evaluate VariableDeclarationList.

  2. Evaluate VariableDeclaration.

所以在#2 被执行时,#1 已经被评估了,你可以在#2 中使用它的任何效果。

关于javascript - 奇怪但有效的 var 声明语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533946/

相关文章:

javascript - 切换设备工具栏时 React Js 元素不会调整大小

javascript - Bootstrap Collapse Button 如何防止出现两次折叠

javascript - 循环结束后打印计数器的最简单方法是什么?

javascript - Ionic - 检查 Typescript 中的 ""

javascript - 突然丢失 Visual Studio Typescript Intellisense

javascript - 运行初始数组后,Jquery 数组返回未定义

javascript - Chrome 扩展程序 : How to open a specified link in a new tab by clicking a button in the html popup?

javascript - 在 MEAN Web 应用程序中,从 Express(服务器端)发送 HTTP 响应错误 403、500,未在 Angular Controller 的 errorCallback 函数中捕获

javascript - 尝试将产品部分移动到侧栏 x-cart 5 中类别部分的下方

javascript - 获取 HTML Body 中的 Javascript 变量