2013-04-23 44 views
8

考虑以下几点:阵图和parseInt函数愁楚

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

为什么不是输出,而不是:或者使用parseFloat

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

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

[10, 0, 0, 1] 

尽管下面拿着真确实给了我想要的输出;但是我觉得我错过了一些关键的东西。

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

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

+1

http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint http://stackoverflow.com/questions/8594699/map-parseint-strange-results – 2013-04-23 00:39:47

回答

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] 
+0

+1,for速度和准确性! – 2013-04-23 00:40:35

+0

谢谢! 我知道它会是这样的,但不确定搜索条件。 – dcousens 2013-04-23 00:41:23

+0

很好的答案+1。你给的例子正是我的绊脚石!我想知道为什么我在Chrome和Firefox上获得不同的结果,但这是因为基数未定义时的行为取决于实现。我现在对Mozilla文档为什么说“在使用'parseInt'时总是指定一个基数” – xlm 2014-12-17 14:16:59