Thoughts on JavaScript Array Loops

Source: Internet
Author: User
Tags javascript array

View Code , Do not speak: Copy code The Code is as follows: var I = arr. length;
While (I --)
{
// Write something?
}

Above is Google array. jsProgramCode to be improved. Think about why I -- when I is 0, the while loop is over?

The following code is equivalent to it:Copy codeThe Code is as follows: var I = arr. length;
For (; I --;)
{
// I -- is it strange to write it in the middle of two semicolons? Isn't it strange?
}

Shocking? No feeling?

Er. What do we usually write in the middle of two semicolons? This I-according to "Common Sense" should be after the second semicolon. Let's look at the C language code:Copy codeThe Code is as follows: int main ()
{
Int I = 5;
While (I --)
{
Printf ("% d", I );
}
While (1 );
Return 0;
}

The running result is surprisingly consistent with that of JavaScript!

Okay. I don't know why? Only if the value 0 is converted to a Boolean value of false:

VaR I = !! 0;

Other values are converted to a Boolean value of true. The code in the preceding example explicitly converts a value to a Boolean value.

Use the following JS program to test the implicit conversion of 0 to false:Copy codeThe Code is as follows: var I = 0;
If (I)
{
Alert ('if ');
}
Else {
Alert ('else ');
}
Alert ('the if and else programs should all come here ');

If this sample code is not "practical" at all "? Well, the following is a sample code snippet from a front-end developer of Tudou:Copy codeThe Code is as follows: var OBJ = {status: 0, MSG: 'xxxx '};
VaR DATA = obj. Status | 'xxxx ';

This is always "hidden!

once again, it is emphasized that the implicit conversion of the value 0 to the condition where the Boolean value is false is in if (), while (), (;;) conditional expressions for Boolean judgments such as the middle of two semicolons.

Related Article

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.