JavaScript逗号运算符用法解析

2021年3月16日16:41:48 发表评论 972 次浏览

下面是逗号运算符的示例。

例子:

<script> 
     function x() { 
         document.write( 'one' + "</br>" ); 
         return 'one' ; 
     } 
     function y() { 
         document.write( 'two' + "</br>" ); 
         return 'two' ; 
     } 
     function z() { 
         document.write( 'three' + "</br>" ); 
         return 'three' ; 
     } 
  
     // Three expressions are 
     // given at one place 
     var x = (x(), y(), z()); 
  
     document.write(x); 
</script>

输出如下:

one
two
three
three

JavaScript中的逗号运算符(, )的使用方式与许多编程语言(如C, C ++, Java等)所使用的方式相同。该运算符主要按从左到右的顺序计算其操作数, 并返回最右边的操作数的值。 。在需要单个表达式的位置, 逗号运算符用作多个表达式的分隔符。将逗号运算符放在表达式中时, 它将执行每个表达式并返回最右边的表达式。

语法如下:

Expression1, Expression2, Expression3, ....so on

在以上语法中, 使用逗号运算符分隔了多个表达式。在执行过程中, 每个表达式将从左到右执行, 并返回最右边的表达式。

例子:

<script>
     function x() {
         document.write( 'Welcome' );
         return 'Welcome' ;
     }
     function y() {
         document.write( 'to' );
         return 'to' ;
     }
     function z() {
         document.write( 'lsbin' );
         return 'lsbin' ;
     }
  
     // Three expressions are 
     // given at one place
     var x = (x(), y(), z());
  
     document.write(x);
</script>

输出如下:

JavaScript逗号运算符1

在输出中, 首先执行函数x(), 然后执行y(), 最后执行z()。最后, 逗号运算符返回最右边的表达式。

逗号运算符最有用的应用是循环。在循环中, 它用于更新同一表达式中的多个变量。

例子:

<script> 
for ( var a = 0, b =5; a <= 5; a++, b--) {
   document.write(a, b);
}
</script>

输出如下:

JavaScript逗号运算符2

支持的浏览器:

  • 谷歌浏览器
  • IE浏览器
  • 火狐浏览器
  • 苹果Safari
  • 歌剧

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: