`
MirrorAvatar
  • 浏览: 46426 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ECMAScript中逗号操作符少见的用法

阅读更多

引言:有的公司面试前端开发的时候,可能会问JavaScript逗号操作符的问题,详情请参考文章最后的链接。

 

知识结构:



 

 

JavaScript逗号操作符,在MDN上是这么说的:

 

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

    大意是“逗号操作符会从左到右计算每个操作数的值,然后返回最后一个操作数的值”。

 

这应该是个少见的用法,平时开发中也没遇到过,如有例子,感谢您提供一下。下面说一下常用的用法和这个不常用的。

  1. 逗号可以用于变量声明,例:
    var a,b,c,d,e;
    有个细节需要注意的是:这里的逗号不算是个操作符,原因还是MDN上的解释:
    Note that the comma in the var statement is not the comma operator, because it doesn't exist within an expression. Rather, it is a special character in var statements to combine multiple of them into one. Practically, that comma behaves almost the same as the comma operator, though.
    还有个东西需要提出的是,百度JavaScript规范中,不推荐这种变量的声明方式,更推荐的是每个var只声明一个变量
    [强制] 每个 var 只能声明一个变量。

    解释:

    一个 var 声明多个变量,容易导致较长的行长度,并且在修改时容易造成逗号和分号的混淆。
    我同意百度的用法。
  2. 用于隔开函数参数、对象的属性。例子:
    function foo(a, b) {
        //code goes here
    }
    
    var person={
    	name:"Byron",
    	age:"24"
    };
     注意这些逗号也不是逗号操作符。
  3. 逗号操作符用在for循环当中。这个用法的依据就是文章刚开始说的:The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.例子:
    for (var i = 0, j = 9; i <= 9; i++, j--) {
    
        console.log("a[" + i + "][" + j + "]);
    
    }
     
  4. 还有个用法,不常见,MDN上提供的:Processing and then returning(执行然后返回):
    function myFunc () {
      var x = 0;
    
      return (x += 1, x); // the same of return ++x;
    }
     这个用法和 ++ x一个用法,感觉没啥意义。

参考资料:

JavaScript面试时候的坑洼沟洄——逗号、冒号与括号

 

 

 

 
  • 大小: 332.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics