Home > Web Front-end > JS Tutorial > body text

JavaScript中逗号运算符介绍及使用示例_javascript技巧

WBOY
Release: 2016-05-16 16:09:30
Original
1223 people have browsed it

有一道js面试题,题目是这样的:下列代码的执行结果是什么,为什么?

复制代码 代码如下:

var i, j, k;
for (i=0, j=0; i   k = i+j;
}
document.write(k);

答案是显示10,这道题主要考察JavaScript的逗号运算符。

下面是MDN对逗号运算符的定义:

逗号运算符计算两个操作数(从左至右)并返回第二个操作数的值。

根据这个定义,可以扩展一下:

逗号运算符从左到右计算两个或多个操作数并返回最后一个操作数的值。

可以感觉一下下面的代码:

复制代码 代码如下:

alert((0, 9));
alert((9, 0));

if (0,9) alert("ok");
if (9,0) alert("ok");

逗号运算符在实际代码中有什么样的作用呢?

1、交换变量,无需第三个变量

复制代码 代码如下:

var a = "a", b = "b";

//方法一
a = [b][b = a, 0];

//方法二
a = [b, b = a][0];

2、简化代码

复制代码 代码如下:

if(x){
  foo();
  return bar();
}
else{
  return 1;
}

可以简写成:

复制代码 代码如下:

return x ? (foo(), bar()) : 1;
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!