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

สะสมค่าโดยใช้ Callback และค่าเริ่มต้นใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ ฟังก์ชัน callback และค่าเริ่มต้น

ฟังก์ชันควรสะสมค่าในการวนลูปอาร์เรย์และคืนค่าสุดท้าย เช่นเดียวกับ Array.prototype.reduce()

ตัวอย่าง

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

const arr = [1, 2, 3, 4, 5]; 
const sum = (a, b) => a + b;
Array.prototype.customReduce = function(callback, initial){
  if(!initial){
    initial = this[0];
  }
  let res = initial;
  for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){
    res = callback(res, this[i]);
  }
  return res;
};
console.log(arr.customReduce(sum, 0));

ผลลัพธ์

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

15