สมมติเรามีอาร์เรย์ของออบเจ็กต์แบบนี้:
const arr = [ { duration: 10, any: 'fields' }, { duration: 20, any: 'other fields' }, { duration: 15, any: 'some other fields' } ];เราต้องเขียนฟังก์ชันที่รับอาร์เรย์แบบนี้และคืนค่าผลรวมของคุณสมบัติ duration ของทุกออบเจ็กต์
สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็น 45
ตัวอย่าง
โค้ดสำหรับนี้:
const arr = [ { duration: 10, any: 'fields' }, { duration: 20, any: 'other fields' }, { duration: 15, any: 'some other fields' } ]; const addDuration = arr => { let res = 0; for(let i = 0; i < arr.length; i++){ res += arr[i].duration; }; return res; }; console.log(addDuration(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
45