开发者

comma operator returns the value of the second operand?

The links

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

says

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

and as an example

for (var i=0, j=9; i 开发者_如何学编程<= 9; i++, j--)
  document.writeln("a["+i+"]["+j+"]= " + a[i][j]);

Unable to understand the point exactly. "returns the value of the second operand" - What it means?

Thanks for any help in advance.


Is as simple as described:

console.log((1,2) == 2); // true

The expression (1,2) will returns the value of the second operand (2).

Edit: The example you post, is not really good to exemplify the 'return value' of the comma operator, since the value of the increment expression on a for loop is not used. That expression is evaluated but nothing is done with its return value.

for ([initialExpression]; [condition]; [incrementExpression])
   statement


See the for loop index adjustments

7:~$ js
js> 1,2
2
js> 1,2,3
3
js> 1,2,3,4
4
js> 

The idea is that the first expression will be evaluated purely for side-effects such as assignment. The value of the entire expression is the value of the right operand of the , operator.

It is frequently the case that neither of the expressions is being evaluated for its value. In your example case the use of the , operator is to cram two index adjustments into the third expression of the for loop. Neither value is used, it's purely for side effects. Here is a more involved example:

js> i = 10; j = 20;
20
js> t = i++, j--;
20
js> i
11
js> j
19
js> t
10

You can see that both expressions were evaluated (so i and j were bumped) but the value of t is the value of the second expression, j--.


var m = (false, "string");
m === false; // is false
m === "string"' // is true

It actually works for an arbitary number of operands:

var n = (1,2,3,4,5,6);
n === 6; // is true


I think it's clearer to demonstrate using functions:

console.clear();
function a() {
   console.log('function a executed, its return value is \'ignored\'');
   return 1;
}
function b() {
   console.log('function b executed and expression (a(),b()) will evaluate to the return value from b');
   return 2;
}
console.log((a(),b())==2);

outputs:

function a executed, its return value is 'ignored'
function b executed and expression (a(),b()) will evaluate to the return value from b
true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜