使用逗号分配是否有效? [英] Does assignment with a comma work?

查看:115
本文介绍了使用逗号分配是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 aaa = 1,2,3 工作并将 aaa 的值设置为 1

Why does aaa = 1,2,3 work and set the value of aaa to 1?

为什么不 var bbb = 1,2,3 工作?

为什么 var bbb =(1,2,3)工作并设置<的值code> bbb 到 3

推荐答案

有一个这里有很多,但基本上,它归结为逗号运算符

There's a lot going on here, but basically, it comes down to the comma operator.


逗号运算符计算其两个操作数(从左到右)并返回第二个值操作数。

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.






此代码:


This code:

aaa = 1,2,3

是相当于:

aaa = 1;
2;
3;

所以 aaa 被隐式声明并分配了值1.请注意,控制台上的输出是最后一个语句的结果,3。

So aaa is implicitly declared and assigned a value of 1. Notice that the output on the console is the result of the last statement, 3.

此代码:

var bbb = 1,2,3

是语法错误,因为变量声明中的逗号用于在一行中声明多个变量。正如MDN文章指出的那样,

Is a syntax error because commas in variable declarations are used to declare multiple variables in a single line. As the MDN article points out,


请注意 var 语句中的逗号是 逗号运算符,因为它在表达式中不存在。相反,它是 var 语句中的一个特殊字符,用于将它们中的多个组合成一个。

Note that the comma in the var statement is not the comma operator, because it doesn't exist within an expression. Rather, it is a special character in var statements to combine multiple of them into one.

所以这段代码大致相当于:

So this code is roughly equivalent to:

var bbb = 1;
var 2;
var 3;

当然, 2 无效标识符,所以它在那时失败了。

Of course, 2 is not a valid identifier, so it fails at that point.

此代码:

var bbb = (1,2,3)

与第一个非常相似,除了因为数值包含在括号中,所以首先评估它们。所以这相当于:

Is very similar to the first, except because the numeric values are wrapped in a parentheses, they are evaluated first. So this is rougly equivalent to:

1;
2;
var bbb = 3;

这篇关于使用逗号分配是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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