Is there or isn't there an integer type in JavaScript?

前端 未结 4 1473
南旧
南旧 2020-12-29 01:19

I am just starting to learn Javascript and I immediately got confused by seemingly contradictory statements in Mozilla\'s A re-introduction to JavaScript (JS tutorial).

相关标签:
4条回答
  • 2020-12-29 01:36

    I should mention that there is actually a type called BigInt which represents a true integer.

    However, because it can't be used with Number and is generally only a good idea to use for larger numbers, I wouldn't advise it.

    I thought it was worth a mention though.

    var n = BigInt(1337);
    console.log(typeof n); //prints "bigint"
    
    0 讨论(0)
  • 2020-12-29 01:38

    I believe questioner has already found his/her answer. But for others like me, you can check number is integer or not in JavaScript by using Number.isInteger() method. MDN

    0 讨论(0)
  • 2020-12-29 01:42

    UPDATE: with a new ES2020 standard released this answer is not entirely correct anymore, see the other answer (from @Mathias Lykkegaard Lorenzen) about BigInt details.

    There is only the Number data type in JS that represents numbers.

    Internally it is implemented as IEEE 754 double precision floating point number.

    What it means is that - technically there is no dedicated data type that represents integer numbers.

    Practically it means that we can safely use only numbers that are safely representable by the aforementioned standard. And it includes integer values in the range: [-9007199254740991; 9007199254740991]. Both values are defined as constants: Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER correspondingly.

    0 讨论(0)
  • 2020-12-29 02:03

    Ah yes, this can be quite confusing. In Javascript, the type of a variable is implicitly defined.

    the function parseInt will simply not take the decimal point into account and the type of the result would be an int.

    0 讨论(0)
提交回复
热议问题