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

查看:54
本文介绍了为什么 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中的回调函数有三个参数:

来自您链接到的同一个 Mozilla 页面:

From the same Mozilla page that you linked to:

使用三个参数调用回调:元素的值、元素的索引和正在遍历的 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天全站免登陆