数组映射和parseInt问题

时间:2013-04-23 00:32:43

标签: javascript string

鉴于以下内容:

> '10.0.0.1'.split('.').map(parseInt)
[10, NaN, 0, 1]

为什么不输出输出:

[10, 0, 0, 1]

尽管如下:

> x = '10.0.0.1'.split('.');
["10", "0", "0", "1"]

> x[1] == x[2]
true

或者使用parseFloat确实可以获得所需的输出;但是我觉得我在这里缺少一些至关重要的东西。

编辑: '10.0.0.1'.split('.').map(function(x) { return parseInt(x); })按预期工作。

EDIT2 :我使用的是Chrome版本26.0.1410.64,但这也发生在我的node.js本地副本中。

2 个答案:

答案 0 :(得分:10)

请查看此链接的底部,在“棘手的用例”中解释NaN

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map

通常使用带有一个参数的回调(被遍历的元素)。一些函数也常用于一个参数。这些习惯可能导致行为混乱。

// Consider:
["1", "2", "3"].map(parseInt);
// While one could expect [1, 2, 3]
// The actual result is [1, NaN, NaN]

// parseInt is often used with one argument, but takes two. The second being the radix
// To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array
// The third argument is ignored by parseInt, but not the second one, hence the possible confusion.
// See the blog post for more details

// Solution:
function returnInt(element){
  return parseInt(element,10);
}

["1", "2", "3"].map(returnInt);
// Actual result is an array of numbers (as expected) [1, 2, 3]

答案 1 :(得分:1)

快速解决方案,使用parseFloat

'10.0.0.1'.split('.').map(parseFloat); //=> [10,0,0,1]

为什么parseInt无法正常工作?在这里回答:javascript - Array#map and parseInt

相关问题