【问题标题】:comma operator returns the value of the second operand?逗号运算符返回第二个操作数的值?
【发布时间】:2010-12-13 22:45:58
【问题描述】:

链接

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

逗号运算符同时计算 它的操作数(从左到右)和 返回第二个的值 操作数。

作为一个例子

for (var i=0, j=9; i <= 9; i++, j--)
  document.writeln("a["+i+"]["+j+"]= " + a[i][j]);

无法准确理解重点。 “返回第二个操作数的值”——这是什么意思?

提前感谢您的帮助。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    就像描述的那样简单:

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

    表达式 (1,2) 将返回第二个操作数 (2) 的值。

    编辑:您发布的示例并不是很好地举例说明逗号运算符的“返回值”,因为未使用for 循环上的增量表达式的值。该表达式被求值,但没有对其返回值做任何事情。

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

    【讨论】:

    • 哦,但现在你要让他继续=== vs == :)
    • @CMS 感谢您的评论。但我无法将其与示例联系起来。
    • 好吧,实际上我在这个例子中不需要===,因为我知道这两种类型都是数字...... :)
    • 这是因为在示例中,这些表达式的返回值与循环的操作方式无关。即,不以任何方式使用返回值。逗号运算符仅用于执行两个表达式,而不用分号分隔。
    • @Peter Bailey,@CMS。我现在明白了。感谢您的时间和努力。
    【解决方案2】:

    查看for循环索引调整

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

    这个想法是,第一个表达式将纯粹针对诸如赋值之类的副作用进行评估。整个表达式的值就是,运算符的右操作数的值。

    通常情况下,两个表达式都没有被评估其值。在您的示例中,, 运算符的使用是将两个索引调整塞入for 循环的第三个表达式中。这两个值都没有使用,它纯粹是为了副作用。这是一个更复杂的例子:

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

    您可以看到两个表达式都被计算了(所以ij 被碰撞了)但是t 的值是第二个表达式j-- 的值。

    【讨论】:

      【解决方案3】:
      var m = (false, "string");
      m === false; // is false
      m === "string"' // is true
      

      它实际上适用于任意数量的操作数:

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

      【讨论】:

        【解决方案4】:

        我认为使用函数演示更清楚:

        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);
        

        输出:

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

        【讨论】:

          猜你喜欢
          • 2011-07-31
          • 1970-01-01
          • 1970-01-01
          • 2013-11-22
          • 2013-01-12
          • 2016-10-28
          • 2021-10-06
          • 1970-01-01
          • 2016-04-13
          相关资源
          最近更新 更多