JavaScript map+parseInt 容易产生的误区

时间:2020-07-23 09:18:07   收藏:0   阅读:67

map

/**
 * 语法:
 * var new_array = arr.map(function callback(currentValue[,index[,array]]){
 *  // return element for new_array
 * }[,thisArg])
 */

简单示例

var numbers = [1, 4, 9]
var double = numbers.map(x => x * 2)
console.info(double)

parseInt in map

const newIntArray = ["1", "2", "3"].map(parseInt)
console.info(newIntArray) // [ 1, NaN, NaN ]

解析过程

解决办法: 使用箭头函数

const newIntArrayWithNumber = ["1.2", "2.3", "3.4"].map(num => parseInt(num, 10))
console.info(newIntArrayWithNumber) // [ 1, 2, 3 ]
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!