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

Thoughts caused by JavaScript array loop_javascript skills

WBOY
Release: 2016-05-16 18:37:39
Original
1112 people have browsed it

Look at the code without talking:

Copy the code The code is as follows:

var i=arr.length ;
while(i--)
{
//Write something?
}

The above is the code of Google array.js program that suggests improvements . Think about why i-- the while loop ends when i is 0?

The following code is equivalent to it:
Copy the code The code is as follows:

var i=arr.length;
for(;i--;)
{
//i-- is written in the middle of two semicolons, is it strange? Isn't it strange?
}

Shocked? Not feeling it?

Ugh. What do we usually write between the two semicolons? This i--according to "common sense" should be after the second semicolon. Then let’s take a look at the C language code:
Copy the code The code is as follows:

int main( )
{
int i = 5;
while(i--)
{
printf("%d ", i);
}
while(1) ;
return 0;
}

The running result is also amazingly consistent with JavaScript!

Okay. I don't know why? We only know that the value 0 is converted into a Boolean value and is false:

var i= !!0;

and other values ​​are converted into a Boolean value and is true. The example program code above is an explicit conversion of a numeric value to a Boolean value. If

0 is implicitly converted to false, use the following JS program to test:
Copy code The code is as follows :

var i=0;
if(i)
{
alert('if');
}
else{
alert( 'else');
}
alert('No matter what the if and else programs are, they have to go here');

if This example code is not written in a "practical" way at all ? Well, here is a code sample snippet from a Tudou.com front-end development expert:
Copy the code The code is as follows:

var obj = {status:0, msg:'xxxx'};
var data = obj.status || 'xxxx';

This is always "hidden" "Yes!"

I emphasize again: the implicit conversion of value 0 into a Boolean value of false is determined by Boolean decisions in if(), while(), and between the two semicolons of for(;;) Conditional expression.
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