Search code examples
javascriptarraysdigit

Why is the last element of my array being replaced with a 0


I have a function:

function splitToDigits(n) {
    var digits = ("" + n).split("").map(function(item) {
        return parseInt(item, 10);
    });
    console.log(digits);
}

console.log(splitToDigits(123456784987654321));

This is returning digits = [1,2,3,4,5,6,7,8,4,9,8,7,6,5,4,3,2,0].

Any idea why the last element is 0? I noticed that when I delete 2 elements from the array it acts normally. Thanks for all the great answers! :)


Solution

  • As Jaromanda X mentioned in the comments section above, JavaScript does not have enough precision to keep track of every digit in the integer you passed to your function.

    To fix this problem, you should instead pass a string:

    console.log(splitToDigits('123456784987654321'))
    

    However, I would also like to point out that you can greatly simplify your splitToDigits method:

    function splitToDigits(n) {
      return [].map.call(n + '', Number)
    }
    
    console.log(splitToDigits('123456784987654321'))
    console.log(splitToDigits(1234))