数组的map方法和parseInt函数的问题

11

给定以下内容:

> '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); })按预期工作。

编辑2:我正在使用Chrome版本26.0.1410.64,但这也发生在我的本地node.js副本中。


1
https://dev59.com/nHVC5IYBdhLWcg3wihqv https://dev59.com/p17Va4cB1Zd3GeqPKoh0 - Josh Lee
2个回答

12

请查看此链接底部的“棘手用例”,其中解释了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, for speed and accuracy ! - Gabriele Petrioli
我知道会是这样的,但不确定搜索条件。谢谢! - deceleratedcaviar
很棒的答案 +1。你给出的例子正是困扰我的问题!我一直在想为什么在Chrome和Firefox上得到不同的结果,但这是因为当基数未定义时的行为取决于实现。现在我更加明白为什么Mozilla文档中说“使用parseInt时始终要指定基数”。 - xlm

2

快速解决方案,使用parseFloat

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

为什么parseInt不能按预期工作?在这里回答:javascript-数组#map和parseInt


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接