2013-04-23 54 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