获得NaN的不一致映射parseInt函数 [英] Getting NaN inconsistently mapping parseInt

查看:209
本文介绍了获得NaN的不一致映射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)


解决方案

这是因为函数传递到的 地图 将与三个参数来调用:


  1. 当前数组项

  2. 该项目的索引

  3. 全阵列式

在这种情况下,该功能是 parseInt函数 ,仅使用两个参数:


  1. 将要分析的字符串

  2. 用来解析字符串的基数

  3. 其他参数将被忽略。

因此​​,对于数组中的第二项(即指数 1 ),呼叫将被

parseInt函数(0,1,ignoredArray)

在基数 1 NaN的则返回:


  

      
  • 我们的研究 基数的)。

  •   
  • 如果研究的≠0,则
      
      

        
    • 如果研究的< 2或研究的> 36,然后返回为NaN

    •   

  •   

另外请注意,如果你使用像一个更大号新阵列(99),你会看到 NaN的 S开始在指数37。

Was playing around with some code to create an array of 0's and found that for only one value NaN was returned instead of 0. 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:

  1. The current array item
  2. The index of that item
  3. The whole array

In this case, that function is parseInt, which only uses two arguments:

  1. The string to be parsed
  2. The radix used to parse the string
  3. Additional arguments will be ignored.

Therefore, for the 2nd item in the array (i.e. index 1), the call will be

parseInt("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 seen NaNs starting at index 37.

这篇关于获得NaN的不一致映射parseInt函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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