我正在阅读一篇声明_.parseInt安全的博客。 根据文档,它也接受基数作为本机parseInt的第二个参数。 通常在映射数组时,直接将parseInt传递给map时会遇到意外行为。
lodash的parseInt如何安全地工作?
var a = ['2', '3', '4', '5', '6', '7', '8']
//case 1:
_.map(a, parseInt)
//[2, NaN, NaN, NaN, NaN, NaN, NaN] - this is the expected output
//case 2:
_.map(a, (num, index) => _.parseInt(num, index))
//[2, NaN, NaN, NaN, NaN, NaN, NaN] - this is the expected output
//case 3:
_.map(a, _.parseInt)
//[2, 3, 4, 5, 6, 7, 8] - how is this working correctly?
案例2与案例3有什么不同?
答案 0 :(得分:1)
_.parseInt
的{{3}}采用“秘密”第三个参数。
如果提供了第三个参数,就像在_.map(a, _.parseInt)
回调中一样,则忽略第二个参数。
var a = ['2', '3', '4', '5', '6', '7', '8'];
// With two arguments:
console.log(_.map(a, (num, index) => _.parseInt(num, index)));
//[2, NaN, NaN, NaN, NaN, NaN, NaN] - this is the expected output
// With all three arguments that _.map provides:
console.log(_.map(a, (num, index, arr) => _.parseInt(num, index, arr)));
//[2, 3, 4, 5, 6, 7, 8]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>