JavaScript,声明变量时语法混乱 [英] JavaScript, confusing syntax when declaring a variable

查看:28
本文介绍了JavaScript,声明变量时语法混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在我正在阅读的一本 JavaScript 书中遇到了以下代码行:

var col = [], top, bottom;

这是我第一次遇到一个变量似乎被赋予了三个变量.有人可以解释这行代码中发生了什么吗?

I recently came across the following line of code in a JavaScript book that I am working through:

var col = [], top, bottom;

This is the first time I've encountered a variable seemingly being given three variables. Could someone explain what is happening in this line of code?

推荐答案

这只是一个简短的版本:

It is simply a shorter version of this:

var col = [];
var top;
var bottom;

一种风格相对于另一种风格没有真正的优势/劣势,但是 JSLint 喜欢拥有所有 var 在每个范围内组合的声明(如您的问题):

There is no real advantage/disadvantage of one style over the other, but JSLint likes to have all var declarations in each scope combined (as you have in your question):

在具有块作用域的语言中,通常建议变量在第一次使用的地方声明.但是因为 JavaScript没有块作用域,更明智的做法是声明一个函数的所有函数顶部的变量.建议单每个函数使用 var 语句.

In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function.

<小时>

有关为什么会出现这种情况的完整解释,您可以查看 ECMAScript 规范.这是语法的相关部分:


For a full explanation of why this is the case, you can have a look at the ECMAScript spec. Here's the relevant part of the grammar:

VariableStatement : var VariableDeclarationList ;

VariableStatement : var VariableDeclarationList ;

VariableDeclarationList : VariableDeclaration VariableDeclarationList , VariableDeclaration

VariableDeclarationList : VariableDeclaration VariableDeclarationList , VariableDeclaration

VariableDeclaration : 标识符初始化器opt

还值得注意的是,此处使用的逗号与不相同rel="nofollow">逗号运算符.只是碰巧使用了相同的字符.

It's also worth noting that the commas used here are not the same as the comma operator. It just happens to use the same character.

这篇关于JavaScript,声明变量时语法混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆