在使用REDUTE()的同时使用子字符串

2022-05-24 00:00:00 reduce javascript

我正在尝试使用REDUTE从数组中获取总长度。但是当我看到长度前缀是‘KM’时,我遇到了一个问题。所以我试着去掉‘KM’(子串),然后加上长度。以下是我到目前为止所做的:

this.totalLength= this.roads.map((road) => road.distance)
  .reduce((prev, next) => prev + parseFloat(next.substring(2)));

它正在工作,但没有将数组的第二个值添加到totalLength。

以下是该数组的示例:

[
  {
    "Id": "1",
    "distance": "Km12.20",
    "name": "Hwy1"
  },
  {
    "Id": "2",
    "distance": "Km19.60",
    "name": "Hwy2"
  }
]
    

解决方案

您所做的几乎是正确的。reduce还需要第二个参数,即初始值。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
const roads = [
  {
    "Id": "1",
    "distance": "Km12.20",
    "name": "Hwy1"
  },
  {
    "Id": "2",
    "distance": "Km19.60",
    "name": "Hwy2"
  }
]

roads
  .map((road) => road.distance)
  .reduce((prev, next) => prev + parseFloat(next.substring(2)), 0);

相关文章