Does this 'for' loop stop, and why/why not? for (var i=0; 1/i > 0; i++) { }

后端 未结 3 1917
不思量自难忘°
不思量自难忘° 2021-01-29 22:03

Does this for loop ever stop?

for (var i=0; 1/i > 0; i++) {
}

If so, when and why? I was told that it stops, but I was given no r

3条回答
  •  离开以前
    2021-01-29 22:35

    The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript. The MAX_SAFE_INTEGER constant has a value of 9007199254740991. The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1.

    Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

    Because MAX_SAFE_INTEGER is a static property of Number, you always use it as Number.MAX_SAFE_INTEGER, rather than as a property of a Number object you created.

    UPDATE:

    Someone in an answer that was deleted mentioned: i will never reach infinity. Once it reaches Number.MAX_SAFE_INTEGER, i++ doesn't increment the variable anymore. This is in fact not correct.

    @T.J. Crowder comments that i = Number.MAX_SAFE_INTEGER; i++; i == Number.MAX_SAFE_INTEGER; is false. But the next iteration reaches an unchanging state, so the answer in main is correct.

    i in the example never reaches Infinity.

提交回复
热议问题