SoFunction
Updated on 2025-03-01

Thoughts arising from JavaScript array loops

Look at the code and don't speak:
Copy the codeThe code is as follows:

var i=;
while(i--)
{
//What should I write?
}

The above is GoogleIn the programRecommended improvementscode. Think about why i-- When i is 0, the while loop ends?

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

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

Shocked? Don't feel it?

Well. What do we usually write between two semicolons? This i--according to common sense, it should be after the second semicolon. Let's take a look at the C language code:
Copy the codeThe code is as follows:

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

The results of the run are also surprisingly consistent with JavaScript!

All right. I don't know why this is? Only know that the value 0 is converted to a boolean value to false:

var i= !!0;

The other values ​​are converted to Boolean values ​​to true. The example program code above is an explicit conversion of numeric values ​​to boolean values.

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

var i=0;
if(i)
{
alert('if');
}
else{
alert('else');
}
alert('No matter how if and else program, you have to go here');

If this sample code is not "practical" at all? Well, here is a code sample snippet of a Tudou.com front-end development expert:
Copy the codeThe code is as follows:

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

This is always "hidden" enough!

I would like to emphasize again: the condition that the implicit conversion of the numeric value 0 to the Boolean value false is a conditional expression determined by Boolean in if(), while(), and the middle of the two semicolons such as for(;;).