Home >Web Front-end >JS Tutorial >Thoughts caused by JavaScript array loop_javascript skills

Thoughts caused by JavaScript array loop_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:37:391141browse

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.
Statement:
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