如何計算一組條目之間的總時間?
假設我們有一個數組,其中包含有關高速摩托艇在上游和下游速度的一些資料,如下所示-
以下是我們的示例陣列-
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