为什么 `(['1','2','3']).map(parseInt)` 无法得到正确的结果?

2023-12-22

(['1','2','3']).map(n => parseInt(n));

将返回预期结果[1,2,3]

But:

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

returns [1, NaN, NaN].

哪里错了?


As Array#map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Parameters回调有 3 个参数,第二个参数是index这是造成这个结果的原因。无论function你通过作为callback,此参数作为该函数的参数传递。

第二个论点parseInt https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters is radix hence parseInt('2',1) and parseInt('3',2) is NaN

执行流程将是:

console.log((['1', '2', '3']).map(function(currenValue, index, array) {
  return parseInt(currenValue, index, array);
}));

我会建议你去Number

console.log((['1', '2', '3']).map(Number));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 `(['1','2','3']).map(parseInt)` 无法得到正确的结果? 的相关文章