简体   繁体   English

为什么我的数组的最后一个元素被替换为0

[英]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] . 这是返回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 ? 知道为什么最后一个元素是0吗? I noticed that when I delete 2 elements from the array it acts normally. 我注意到当我从数组中删除2个元素时它会正常运行。 Thanks for all the great answers! 感谢所有伟大的答案! :) :)

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. 正如Jaromanda X在上面的评论部分中提到的,JavaScript没有足够的精度来跟踪传递给函数的整数中的每个数字。

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: 但是,我还想指出,您可以大大简化splitToDigits方法:

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

It's because Javascript is truncating numbers. 这是因为Javascript正在截断数字。

The best way to see this is by doing this console.log: 查看此内容的最佳方法是执行此console.log:

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

Then, when you ran: splitToDigits(123456784987654321) , you already get 123456784987654320. Hence, it has nothing to do with your code as you have still not processed it. 然后,当你运行: splitToDigits(123456784987654321) ,你已经得到123456784987654320.因此,它与你的代码无关,因为你还没有处理它。

If you add digits, it changes to scientific notation: 如果添加数字,则会更改为科学记数法:

splitToDigits(1234567849876543211521521251) // turns to 1.2345678498765432e+27

It's a Javascript precision issue. 这是一个Javascript精度问题。 That's all :) 就这样 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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