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

Introduction and usage examples of comma operator in JavaScript_javascript skills

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

There is a js interview question, the question is this: What is the execution result of the following code and why?

Copy code The code is as follows:

var i, j, k;
for (i=0, j=0; i<10, j<6; i , j ) {
k = i j;
}
document.write(k);

The answer is 10. This question mainly examines JavaScript’s comma operator.

The following is MDN’s definition of the comma operator:

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

According to this definition, it can be expanded:

The comma operator evaluates two or more operands from left to right and returns the value of the last operand.

You can feel the code below:

Copy code The code is as follows:

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

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

What role does the comma operator play in actual code?

1. Exchange variables, no third variable is needed

Copy code The code is as follows:

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

//Method 1
a = [b][b = a, 0];

//Method 2
a = [b, b = a][0];

2. Simplified code

Copy code The code is as follows:

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

can be abbreviated as:

Copy code The code is as follows:

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