使用多个逗号分隔值的 return 语句

可能的复制品:
Javascript 语法: 逗号是什么意思?

这个模式返回什么? 它是如何工作的?

return myfunc(), myobj.myvar = someobj.prop, myobj

我以前没有遇到过这种模式,但是我一直在研究 Bing Maps Ajax 控件,并且多次注意到这种模式。

据我所知,不会返回多个值。那么这个模式是做什么的呢?什么东西回来了?这种模式的好处是什么?

22626 次浏览

It's the comma operator. It evaluates its left-hand operand, throws the result away, evalutes its right-hand operand, and takes that as its result value. It's left-to-right associative, so a, b, c evaluates a, then b, then c, and takes the result of c as its value.

In your example, it's exactly like:

myfunc();
myobj.myvar = someobj.prop;
return myobj;

Some people really prefer to do things on one line, even when there's no objective reason to. There no benefit in the example you gave, and in fact it's confusing because it makes it look like the first two bits relate to the value that will ultimately be returned, which they don't. (I wrote that before you told us it was minified code; obviously, being unclear to humans is only an issue in source code, not minified code.)

Since you've said it's a minifier: The very small possible benefit the minifier might have gotten there is if this is part of a conditional block: It can save one or two characters. If we assume the long form looked like this:

if (someCondition) {
myfunc();
myobj.myvar = someobj.prop;
return myobj;
}

...using the comma operator, the minifier can do this (63 characters):

if(someCondition)return myfunc(),myobj.myvar=someobj.prop,myobj

...rather than this (65 characters):

if(someCondition){myfunc();myobj.myvar=someobj.prop;return myobj}

...without changing the functionality of the code, if what follows is a } or some other appropriate character (or end-of-file) to trigger automatic semicolon insertion at the end. Otherwise, it would need the ; on the first one, but that still saves one character.

The comma operator evaluates (from left to right) the expressions and then it returns the last result, which in this case will be the evaluation of the myobj identifier.

You can do this eliminate some curly braces if that's important to you...

if (true)
;// do something
else
return myfunc(), myobj.myvar = someobj.prop, myobj

...as opposed to...

if (true)
;// do something
else {
myfunc();
myobj.myvar = someobj.prop;
return  myobj;
}

in your example myobj should be returned where as every thing before gets executed

myfunc();
myobj.myvar = someobj.prop;
return myobj;