我目前有一个数字数组

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)

10-08 05:16