如何计算一组条目之间的总时间?
假设我们有一个数组,其中包含有关高速摩托艇在上游和下游速度的一些数据,如下所示-
以下是我们的示例数组-
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
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP