获得NaN的不一致映射parseInt函数 [英] Getting NaN inconsistently mapping parseInt
问题描述
与一些code玩弄创建 0
数组的发现,对于只有一个值 NaN的
被退回,而不是 0
。我得到这个在Chrome中,节点和Firefox。
是什么造成第二个值是 NaN的
?
VAR ARR =新阵列(32)。加入(0).split('')。图(parseInt函数)
//输出[0,NaN时,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0]
console.dir(ARR)
这是因为函数传递到的 地图
将与三个参数来调用:
- 当前数组项
- 该项目的索引
- 全阵列式
在这种情况下,该功能是 parseInt函数
,仅使用两个参数:
- 将要分析的字符串
- 用来解析字符串的基数
- 其他参数将被忽略。
因此,对于数组中的第二项(即指数 1
),呼叫将被
parseInt函数(0,1,ignoredArray)
在基数 1
, NaN的
则返回:
块引用>另外请注意,如果你使用像一个更大号
新阵列(99)
,你会看到NaN的
S开始在指数37。Was playing around with some code to create an array of
0
's and found that for only one valueNaN
was returned instead of0
. I get this in Chrome, Node, and Firefox.What's causing the second value to be
NaN
?var arr = new Array(32).join(0).split('').map(parseInt) // prints [0, NaN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] console.dir(arr)
解决方案That's because the function passed to
map
will be called with three arguments:
- The current array item
- The index of that item
- The whole array
In this case, that function is
parseInt
, which only uses two arguments:
- The string to be parsed
- The radix used to parse the string
- Additional arguments will be ignored.
Therefore, for the 2nd item in the array (i.e. index
1
), the call will beparseInt("0", 1, ignoredArray)
When the radix is
1
,NaN
is returned:
- Let R = ToInt32(radix).
- If R ≠ 0, then
- If R < 2 or R > 36, then return NaN.
Also note that if you used a bigger number like
new Array(99)
, you would have seenNaN
s starting at index 37.这篇关于获得NaN的不一致映射parseInt函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!