逗号运算符如何在js中工作? [英] How does the comma operator work in js?

查看:77
本文介绍了逗号运算符如何在js中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解逗号运算符(,)在JavaScript中的工作方式, 当它不放在括号之间时,它似乎具有不同的行为.

I'm trying to understand how the comma operator (,) works in JavaScript, it seems to have a different behaviour when it's not put between parenthesis.

有人可以解释我为什么吗?

Can someone explain me why ?

示例供参考:

var a = 1; 
var b = 2; 
var c = (a,b);
console.log(c);
//output : as expected 
var c = a,b;
console.log(c);
//output : 1 

标题可能有点混乱. 我的问题是关于昏迷运算符和var归因之间的误解,正如somone解释的那样更进一步

The title might be a bit confusing. My question is about a misconception between the coma operator and var attribution as somone explained further down

因此,此主题不是是该主题的重复

Therefore this subject is not a duplicate of that one What does a comma do in JavaScript expressions?

推荐答案

var c = (a,b);

上面使用逗号运算符.它的值为右手边的值(即b).

The above uses the comma operator. It evaluates as the value of its right-hand side (i.e. b).

var c = a,b;

这不使用逗号运算符.

此处的逗号字符构成var表达式的一部分,该表达式采用逗号分隔的变量列表在当前作用域中创建,每个变量都可以具有可选的赋值.

The comma character here forms part of the var expression which takes a comma-separated list of variables to create in the current scope, each of which can have an optional assignment.

等效于:

var c = a;
var b;

这篇关于逗号运算符如何在js中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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