奇怪的地图行为

时间:2017-02-08 08:00:14

标签: javascript

map(func)map(function(x) { return func(x); })之间的区别是什么?

考虑这个例子:

const lines = '1\n2\n3';
const result = lines.split('\n').map(parseInt);
console.log(result )

这会返回[1, NaN, NaN],这不是我的预期。 但是:

const lines = '1\n2\n3';
const result = lines.split('\n').map(function(x){ return parseInt(x)});
console.log(result)

返回预期的:[1, 2, 3]。这两种形式有什么区别,为什么在第一个例子中结果不是[1, 2, 3]

3 个答案:

答案 0 :(得分:3)

parseInt有第二个参数(基数)。

基本上你执行这个

value index parseInt comment
----- ----- -------- -----------------------------------------------------
  '1'     0        1 with radix 0, and value 1 parseInt assumes radix = 10
  '2'     1      NaN because of the wrong value for the radix
  '3'     2      NaN because of the wrong value for the radix

要转换为数字,您可以使用Number



var lines = '1\n2\n3'

console.log(lines.split('\n').map(Number));




要获取整数值,您也可以使用Math.floor



var lines = '1\n2\n3'

console.log(lines.split('\n').map(Math.floor));




答案 1 :(得分:2)

不同之处在于.map传递给它的函数3参数:

.map(element, index, array)

parseInt函数接受2个参数时

parseInt(string, radix)

因此,您将index作为基数传递。这就是你的结果错误的原因。如果parseInt只接受一个参数就可以工作。

答案 2 :(得分:2)

因为地图中的索引将被传递到地图函数

let lines = '1\n2\n3'
let a = lines.split('\n').map(parseInt);
console.log(a)

// Your code above is expanded as below
a = lines.split('\n').map((x, i) => {
  return parseInt(x, i)
})

console.log(a)

// To fix it, use this
lines.split('\n').map(x => parseInt(x));
相关问题