2014-02-26 72 views
8
['1','2','3'].map(parseInt) 

回报[1, NaN, NaN]是什么[ '1', '2', '3'。图(parseInt函数)导致

我不知道为什么?在我看来是这样的:

['1','2','3'].map(function(i){return parseInt(i,10)}) 

回报[1, 2, 3]

============================== ========================

['1','2','3'].map(parseFloat)
回报[1, 2, 3]

+0

查看地图回调参数 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map –

+0

检查输出:'['1',' 2','3']。map(function(){return arguments});' – fardjad

+0

我相信这个问题已被问过至少3次。 –

回答

4

看看这篇文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

指定的回调函数为:

callback 
Function that produces an element of the new Array, taking three arguments: 
currentValue 
The current element being processed in the array. 
index 
The index of the current element being processed in the array. 
array 
The array map was called upon. 

因此您map()功能扩展为:

parseInt('1', 0, the_array) # 1 
parseInt('2', 1, the_array) # NaN 
parseInt('3', 2, the_array) # NaN 
4

您可以从Mozilla的开发网站找到答案:

// 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 


function returnInt(element){ 
    return parseInt(element,10); 
} 

["1", "2", "3"].map(returnInt); 
// Actual result is an array of numbers (as expected) 

Read more

又读great answer

+1

你的回答很好。但是@霍华德更容易理解,所以我选择了他的答案。非常感谢您的回答。 –

+1

@lemon郑没问题,我很乐意帮助你)) –

相关问题