如何计算条目列表之间的总时间?

javascriptweb developmentobject oriented programming更新于 2025/9/30 0:44:17

假设我们有一个数组,其中包含一些有关摩托艇在上游和下游速度的数据,如下所示 −

以下是我们的示例数组 −

const arr = [{
   direction: 'upstream',
   velocity: 45
}, {
   direction: 'downstream',
   velocity: 15
}, {
   direction: 'downstream',
   velocity: 50
}, {
   direction: 'upstream',
   velocity: 35
}, {
   direction: 'downstream',
   velocity: 25
}, {
   direction: 'upstream',
   velocity: 40
}, {
   direction: 'upstream',
   velocity: 37.5
}]

我们需要编写一个函数,该函数接收此类数组并找出船在整个航程中的净速度(即上游速度 - 下游速度)。

因此,让我们编写一个函数 findNetVelocity(),遍历对象并计算净速度。该函数的完整代码为 −

示例

const arr = [{
   direction: 'upstream',
   velocity: 45
}, {
   direction: 'downstream',
   velocity: 15
}, {
   direction: 'downstream',
   velocity: 50
}, {
   direction: 'upstream',
   velocity: 35
}, {
   direction: 'downstream',
   velocity: 25
}, {
   direction: 'upstream',
   velocity: 40
}, {
   direction: 'upstream',
   velocity: 37.5
}];
const findNetVelocity = (arr) => {
   const netVelocity = arr.reduce((acc, val) => {
      const { direction, velocity } = val;
      if(direction === 'upstream'){
         return acc + velocity;
      }else{
         return acc - velocity;
      };
   }, 0);
   return netVelocity;
};
console.log(findNetVelocity(arr));

输出

控制台中的输出将是 −

67.5

相关文章


有用资源