为什么parseInt会使用Array#map产生NaN? [英] Why does parseInt yield NaN with Array#map?

查看:107
本文介绍了为什么parseInt会使用Array#map产生NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Mozilla开发者网络

[1,4,9].map(Math.sqrt)

将产生:

[1,2,3]

为什么这样做:

['1','2','3'].map(parseInt)

收益此:

[1, NaN, NaN]

我已经在Firefox 3.0.1和Chrome 0.3中测试过,只是作为免责声明,我知道这不是跨浏览器功能(没有IE浏览器) )。

I have tested in Firefox 3.0.1 and Chrome 0.3 and just as a disclaimer, I know this is not cross-browser functionality (no IE).

我发现以下内容将达到预期的效果。但是,它仍然无法解释 parseInt 的错误行为。

I found out that the following will accomplish the desired effect. However, it still doesn’t explain the errant behavior of parseInt.

['1','2','3'].map(function(i){return +i;}) // returns [1,2,3]


推荐答案

Array.map 中的回调函数有三个参数:

The callback function in Array.map has three parameters:

来自相同的 Mozilla页面


使用三个参数调用回调:元素的值,元素的索引和遍历的Array对象。

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed."

所以如果你调用一个函数 parseInt 实际上需要两个参数,第二个参数将是元素的索引。

So if you call a function parseInt which actually expects two arguments, the second argument will be the index of the element.

在这种情况下,您最终依次使用基数0,1和2调用 parseInt 。第一个是不相同的提供参数,因此默认基于输入(在这种情况下为基数10)。基数1是不可能的数字基数,3不是基数2中的有效数字:

In this case, you ended up calling parseInt with radix 0, 1 and 2 in turn. The first is the same as not supplying the parameter, so it defaulted based on the input (base 10, in this case). Base 1 is an impossible number base, and 3 is not a valid number in base 2:

parseInt('1', 0); // OK - gives 1
parseInt('2', 1); // FAIL - 1 isn't a legal radix
parseInt('3', 2); // FAIL - 3 isn't legal in base 2 

所以在这种情况下,你需要包装器功能:

So in this case, you need the wrapper function:

['1','2','3'].map(function(num) { return parseInt(num, 10); });

或ES2015 +语法:

or with ES2015+ syntax:

['1','2','3'].map(num => parseInt(num, 10));

(在这两种情况下,最好显式提供基数 parseInt 如图所示,因为否则根据输入猜测基数。在一些较旧的浏览器中,前导0导致它猜测八进制,这往往是有问题的。它仍然会如果字符串以 0x 开头,则猜测十六进制。)

(In both cases, it's best to explicitly supply a radix to parseInt as shown, because otherwise it guesses the radix based on the input. In some older browsers, a leading 0 caused it to guess octal, which tended to be problematic. It will still guess hex if the string starts with 0x.)

这篇关于为什么parseInt会使用Array#map产生NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆