ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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