2013-04-23 2 views
8

を考えると、次の次の保持真にもかかわらずアレイマップとのparseIntは苦境

[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(parseInt) 
[10, NaN, 0, 1] 

はなぜ代わりに出力されません私に望ましい出力を与えます。しかし、私はここで重要な何かを逃していると感じています。

EDIT:'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 –

答えて

10

ルックは、NaN

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

を説明し、「トリッキーユースケース」で、1つの引数(要素トラバースされている)でコールバックを使用するのが一般的です。いくつかの関数は、1つの引数でもよく使用されます。これらの習慣は、混乱する行動につながる可能性があります。

// 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スピードと正確さ! –

+0

ありがとう! 私はそれがこのようなものであることを知っていましたが、検索基準が不明でした。 – dcousens

+0

偉大な答え+1。あなたが与えた例はまさに私をぶつけていたものです! ChromeとFirefoxで異なる結果が得られたのはなぜだろうか。それは、基数が未定義のときの動作が実装依存であるためです。私は今Mozillaの医者が「いつも 'parseInt'を使うときに基数を指定する」と言った理由について広く理解しています – xlm

1

クイックソリューション、parseFloatを使用します。

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

期待通りparseIntが動作しないのはなぜ?回答:javascript - Array#map and parseInt