Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีคำนวณเวลาทั้งหมดระหว่างรายการต่างๆ

สมมติว่าเรามีอาร์เรย์ที่มีข้อมูลความเร็วของเรือในทิศทางขึ้นน้ำและลงน้ำ

อาร์เรย์ตัวอย่าง

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 }
]

เราต้องเขียนฟังก์ชันรับอาร์เรย์แบบนี้ หา velocity สุทธิ (ความเร็วขึ้นน้ำ - ความเร็วลงน้ำ) ตลอดเส้นทาง

เขียนฟังก์ชัน findNetVelocity() วนลูปอ็อบเจกต์คำนวณ velocity สุทธิ

ตัวอย่าง

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