Introduction to the comma operator in JavaScript and example _ javascript skills

Source: Internet
Author: User
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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.