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]
?
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));