简体   繁体   English

JavaScript 中的逗号运算符:预期语法错误,但代码运行正常

[英]Comma operator in JavaScript: syntax error expected, but code runs OK

I just fixed a few bugs in a trivial web app of mine and stumbled over some interesting lines.我刚刚在我的一个微不足道的网络应用程序中修复了一些错误,并偶然发现了一些有趣的行。 I do not recall why I implemented those lines the way the were.我不记得为什么我按照以前的方式实施这些线路。 Now I changed them to "normal" syntax and all is fine.现在我将它们更改为“正常”语法,一切都很好。 My question just out of curiosity: why did the method work at all ?我的问题只是出于好奇:为什么该方法完全有效? I'd expect a syntax error, but that was not the case.我预计会出现语法错误,但事实并非如此。 The code did work.代码确实有效。

This is the old method implementation:这是旧的方法实现:

ListFillFilter: function(list){
    if (OC.Shorty.Debug) OC.Shorty.Debug.log("using 'default' method to filter filled list");
    // only makes sense for default OC.Shorty list
    var data=new Array();
    data['sum_shortys']=$('#desktop #list-of-shortys tbody tr').length;
    data['sum_clicks']=0;
    $('#desktop #list-of-shortys tbody tr').each(function(){
        data['sum_clicks']+=parseInt($(this).attr('data-clicks'),10);
    });
    OC.Shorty.WUI.Sums.fill.apply(OC.Shorty.Runtime.Context.ListOfShortys,[data]),
    // filter list
    OC.Shorty.WUI.List.filter.apply(this,[list,'target',list.find('thead tr#toolbar th#target #filter').val()]),
    OC.Shorty.WUI.List.filter.apply(this,[list,'title', list.find('thead tr#toolbar th#title #filter').val()]),
    OC.Shorty.WUI.List.filter.apply(this,[list,'status',list.find('thead tr#toolbar th#status select :selected').val()])
    // sort list
    $.when(
        OC.Shorty.Action.Preference.get('list-sort-code')
    ).done(function(pref){
        OC.Shorty.WUI.List.sort(list,pref['list-sort-code']);
    })
}, // OC.Shorty.Runtime.Context.ListOfShortys.ListAddInsert

In the middle you see 5 lines all starting with "OC.Shorty.WUI.Sums.fill.apply".在中间,您会看到 5 行都以“OC.Shorty.WUI.Sums.fill.apply”开头。 These lines are terminated with a comma (",") instead of a semicolon (";").这些行以逗号 (",") 结束,而不是分号 (";")。 Why did that not show up as a syntax error ?为什么这没有显示为语法错误?

Basically, the comma operator groups multiple expressions together, they represent the value of the last expression.基本上, 逗号运算符将多个表达式组合在一起,它们表示最后一个表达式的值。 In your case, you can just as well omit it.在您的情况下,您也可以省略它。

Imagine you have this code:想象一下你有这样的代码:

1
2
3

That is perfectly valid JavaScript code.这是完全有效的 JavaScript 代码。 The numbers are just there to indicate three arbitrary expressions.这些数字只是用来表示三个任意表达式。

If you were to do the following:如果您要执行以下操作:

var expression_value = 1
2
3

expression_value will have the value 1 . expression_value的值为1

If you use the comma operator and parentheses:如果您使用逗号运算符和括号:

expression_value = (1,
2,
3)

It will have the value 3 , because the comma operator returns the value from the rightmost expression.它将具有值3 ,因为逗号运算符从最右边的表达式返回值。

If you don't use any parenthesis, the following parentheses will be implied :如果您不使用任何括号,则将隐含以下括号:

implied = ((expression_value = 1),
2,
3)

expression_value will then have a value of 1 , but implied (ie the entire expression) would now have a value of 3.然后expression_value的值为1 ,但implied的(即整个表达式)现在的值为 3。

This syntax is using the comma operator, , .此语法使用逗号运算符, It evaluate all of its operands and returns the value of the last one.它评估其所有操作数并返回最后一个操作数的值。

The reason one would use this style of coding is so that they can execute the code quickly or on one line.使用这种编码风格的原因是他们可以快速或在一行上执行代码。 Here is an example:这是一个例子:

var a = 0,
    b = 1,
    c;

c = ( a++, b++, a + 2 ); // a is incremented, b is incremented, then c is assigned a + 2

a; // 1
b; // 2
c; // 3

The comma operator marks a sequence;逗号操作符标记一个序列; JS inserts additional ';'s at ends-of-line only if this is necessary to make code parseable. JS在需要使代码可解析时才在行尾插入额外的 ';'。 Therefore, code like因此,像这样的代码

alert("hi"),
alert("there"),
alert("bob") // no semi-colon here

is perfectly valid - it is understood as完全有效 - 它被理解为

alert("hi"),
alert("there"),
alert("bob"); // notice the semi-colon

instead of the (illegal)而不是(非法的)

alert("hi"),;
alert("there"),;
alert("bob");

Relying on auto-insert-of-semicolons is considered bad style , though.不过,依赖自动插入分号被认为是不好的风格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM