2012-08-03 62 views
0

我只是在我的一个简单的Web应用程序中修复了一些错误,并且偶然发现了一些有趣的线条。 我不记得我为什么以这种方式来实现这些行。现在我将它们改为“正常”语法,一切正常。 我的问题出于好奇:为什么这个方法可以工作?我希望有一个语法错误,但事实并非如此。代码确实有效。JavaScript中的逗号运算符:预计会出现语法错误,但代码运行正常

这是旧方法实现:

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 

在中间,你看5日线都开始以“OC.Shorty.WUI.Sums.fill.apply”。这些行以逗号(“,”)而不是分号(“;”)结尾。为什么这不会显示为语法错误?

+0

可能重复的[Javascript语法:什么逗号的意思?](http://stackoverflow.com/questions/3561043/javascript-syntax-what-c​​omma-means) – 2012-08-03 11:41:19

回答

1

基本上,comma operator将多个表达式组合在一起,它们表示最后一个表达式的值。就你而言,你可以忽略它。

想象一下,你有这样的代码:

1 
2 
3 

这是完全有效的JavaScript代码。数字就在那里表示三个任意表达式。

如果你要做到以下几点:

var expression_value = 1 
2 
3 

expression_value将具有价值1

如果用逗号和括号:

expression_value = (1, 
2, 
3) 

它的值将3,因为逗号操作符返回从最右边表达式的值。

如果你不使用任何括号,以下括号将暗示

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

expression_value随后将有1值,但implied(即整个表达)现在会值为3.

1

此语法使用逗号运算符,。它评估它的所有操作数并返回最后一个的值。

人们会使用这种编码方式的原因是,他们可以快速或在一行上执行代码。下面是一个示例:

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 
+0

我认为'加'你的意思是'递增' ? – arkascha 2012-08-03 11:53:40

1

逗号运算符标记一个序列; JS在行尾处插入额外的';',如果这对于使代码可解析是必需的,则只需。因此,像

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

代码是完全有效的 - 它被理解为

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

代替(非法)

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

依托自动插入-的-分号被认为是bad style,但。