This article mainly introduces the introduction and examples of the comma operator in JavaScript. This article describes the definition of the comma operator, the example of use, and some practical skills, you can refer to a js interview question. The question is: What is the execution result of the following code? Why?
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 describes the JavaScript comma operator.
The following is the definition of the MDN comma OPERATOR:
The comma operator calculates two operands (from left to right) and returns the value of the second operand.
According to this definition, you can expand the following:
The comma operator calculates two or more operands from left to right and returns the value of the last operand.
You can feel the following code:
The Code is as follows:
Alert (0, 9 ));
Alert (9, 0 ));
If (0, 9) alert ("OK ");
If (9,0) alert ("OK ");
What is the role of the comma operator in actual code?
1. Swap the variable. No third variable is required.
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
The Code is as follows:
If (x ){
Foo ();
Return bar ();
}
Else {
Return 1;
}
Can be abbreviated:
The Code is as follows:
Return x? (Foo (), bar (): 1;