javascript - 奇怪的 map 行为

标签 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]

最佳答案

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

关于javascript - 奇怪的 map 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42107614/

相关文章:

javascript - 在嵌套的 json 数据 Angular js 的情况下,如何为 ng-options 设置默认值?

javascript - 禁用 Asp.net 按钮,然后使用 java 脚本在 5 秒后启用它

javascript - MongoDB/NodeJS 查询从字典中获取数据

javascript - angularjs ng-show 与新模板

javascript - 如何将我的 meteor 应用程序连接到外部 MongoDB?

javascript - 如何在 Ace Editor 中格式化 XML 代码?

javascript - 从 JSON 结果创建 JSON 结构

javascript - javascript src url 中的动态值

javascript - 将 JS var 传递给 PHP var

javascript - 可汗学院计算机编程中的 Math.random() 与 random()