什么是['1','2','3']。map(parseInt)结果

时间:2014-02-26 08:58:48

标签: javascript

['1','2','3'].map(parseInt)

返回[1, NaN, NaN]

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

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

返回[1, 2, 3]

=============================================== =======
和其他 ['1','2','3'].map(parseFloat)
返回[1, 2, 3]

2 个答案:

答案 0 :(得分:6)

您可以从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 :(得分:5)

查看此文章: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