2015-12-11 107 views
2

有人可以解釋爲什麼我通過執行下面的代碼得到這個奇怪的結果嗎?JavaScript怪異的結果使用parseInt

'1.0.0.0'.split('.').map(parseInt); 

輸出:

[1, NaN, 0, 0] 
+0

重複 http://stackoverflow.com/questions/262427/javascript-arraymap-and-parseint –

回答

2

parseInt函數具有是基數的第二參數。 map傳遞三個參數:currentValue,index和數組。 這意味着數字的索引被用作基數。 試試這個:

'1.0.0.0'.split('.').map(function(s) {return parseInt(s);}); 

https://jsfiddle.net/qbf7u1d7/

+0

感謝您的回答和對不起重複... –

+2

或者,如果您在支持[ES6箭頭函數](https:// www。)的環境中工作,則使用''1.0.0.0'.split('。')。map(x => parseInt(x))''。 google.ca/search?q=ES6+arrow+functions&oq=ES6+arrow+functions&aqs=chrome..69i57.1856j0j7&sourceid=chrome&es_sm=91&ie=UTF-8)。 – meagar