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

ผลรวมดัชนีคู่ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม ฟังก์ชันควรคืนผลรวมของจำนวนเต็มทั้งหมดที่มีดัชนีคู่ คูณกับจำนวนเต็มที่ดัชนีสุดท้าย

const arr = [4, 1, 6, 8, 3, 9];

ผลลัพธ์ที่คาดหวัง:

const output = 117;

ตัวอย่าง

โค้ดด้านล่างนี้

const arr = [4, 1, 6, 8, 3, 9]; 
const evenLast = (arr = []) => {
  if (arr.length === 0) {
    return 0;
  } else {
    const sub = arr.filter((_, index) => index % 2 === 0);
    const sum = sub.reduce((a, b) => a + b);
    const posEl = arr[arr.length - 1];
    const res = sum * posEl;
    return res;
  }
};
console.log(evenLast(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลคือ

117