Integers in JavaScript

后端 未结 5 2073
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 11:25

I\'m a beginner to Javascript so forgive me if I sound dumb because I learned some Javascript from W3Fools (which are really difficult tutorials - they don\'t explain anythi

相关标签:
5条回答
  • 2020-12-01 11:34

    I don't think it ever will support integers. It isn't a problem as every unsigned 32 bit integer can be accurately represented as a 64 bit floating point number.

    Modern JavaScript engines could be smart enough to generate special code when the numbers are integer (with safeguard checks to make sure of it), but I'm not sure.

    0 讨论(0)
  • 2020-12-01 11:38

    If you really need to use integers, just use the floor method on each number you encounter.

    Other than that, the loose typing of Javascript is one of it's strengths.

    0 讨论(0)
  • 2020-12-01 11:44

    There is zero support for integers. It should be a simple matter of rounding off a variable every time you need it. The performance overhead isn't bad at all.

    0 讨论(0)
  • 2020-12-01 11:48

    There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.

    Firefox 4 will have support for Typed Arrays, where you can have arrays of real ints and such: https://developer.mozilla.org/en/JavaScript_typed_arrays

    Until then, there are hackish ways to store integer arrays as strings, and plucking out each integers using charCodeAt().

    0 讨论(0)
  • 2020-12-01 11:54

    Use this:

    function int(a) { return Math.floor(a); }
    

    And yo can use it like this:

    var result = int(2.1 + 8.7 + 9.3); //int(20.1)
    alert(result);                     //alerts 20
    
    0 讨论(0)
提交回复
热议问题