我目前有一个数字数组
data.dataArr = [0: " 1,431,417 "
1: " 1,838,127 "
2: " 679,974 "
3: " 2,720,560 "
4: " 544,368 "
5: " 1,540,370 "]
我正在尝试删除逗号,因此我的数据返回
0: "1431417" , 1: 1838127 ...
除去逗号后,我将映射此数组以将其转换为数字而不是字符串的数组。但是当console.logging应该返回数字数组的finalArray时,我得到
NaN
,我相信这是由于除去逗号的部分。这是我的代码:
let data = {
dataArr: [
" 1,431,417 ",
" 1,838,127 ",
" 679,974 ",
" 2,720,560 ",
" 544,368 ",
" 1,540,370 "
]
};
//removing commas
let arrData = data.dataArr.map(e => e.replace(/(,\s*)+/, ','));
let finalArr = arrData.map(Number);
console.log(finalArr)
或者,我试过了:
let arrData = data.dataArr.replace(/,/g, "")
这导致了
"data.dataArr.replace is not a function"
最佳答案
您可以在相同的map
回调函数中使用数字g
删除所有出现的,
dataArr = [" 1,431,417 ", " 1,838,127 ", " 679,974 ", " 2,720,560 ", " 544,368 ", " 1,540,370 "]
let arrData = dataArr.map(e => Number(e.replace(/(,\s*)+/g, '').trim()));
console.log(arrData)