如何计算条目列表之间的总时间?
假设我们有一个数组,其中包含一些有关摩托艇在上游和下游时的速度的数据,如下所示:
以下是我们的示例数组-
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