简体   繁体   中英

JavaScript: Why is this causing an infinite loop?

I'm trying to find the largest number by finding the point at which the JavaScript number line wraps around. Eg, if it could only hold numbers 0, 1, 127 then I'd find 127 by using the fact that " 127 + 1 = 0 ". So I made a function

function getLargestNumber ( ) 
{
   var somethingBig = 12939123, last = (somethingBig - 1);
   while ( ++somethingBig > ++last );
   return last;
}

but that's causing an infinite loop (or crashing the browser for some other reason).

Is there anything wrong with the logic of my function?

JavaScript numbers are always stored as floating point numbers, not integers like in C. Floating point numbers don't "wrap around" the same way that a C integer will.

This might help you What is JavaScript's highest integer value that a Number can go to without losing precision?

It looks like the while loop will run forever because you are always incrementing both somethingBig and last, therefore somethingBig will always be larger:

while ( ++somethingBig > ++last );

I'm not sure exactly what you are trying to accomplish but this would be the cause of the infinite loop.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM