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