如何计算条目列表之间的总时间?
假设我们有一个数组,其中包含一些有关摩托艇在上游和下游时的速度的数据,如下所示:
以下是我们的示例数组-
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
热门推荐
10 结婚祝福语亲姐姐简短
11 新年发给客户祝福语简短
12 女性生日祝福语简短优美
13 枣庄人事考试祝福语简短
14 致姐姐生日祝福语简短
15 水晶婚夫妻祝福语简短
16 表妹结婚祝福语简短藏语
17 下雪路滑祝福语简短
18 新婚祝福语大全简短经典