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

ฟังก์ชัน JavaScript บนโปรโตไทพ์ของ Array class

ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่อยู่บนโปรโตไทพ์ (prototype) ของคลาส Array ฟังก์ชันนี้รับฟังก์ชัน callback และคืนค่าสมาชิกแรกที่ทำให้ callback คืนค่า true

ควรส่งสมาชิกปัจจุบันและดัชนีปัจจุบันให้ callback เป็นอาร์กิวเมนต์ที่ 1 และ 2

ตัวอย่าง

โค้ดตัวอย่างด้านล่าง:

const arr = [4, 67, 24, 87, 15, 78, 3];
Array.prototype.customFind = function(callback) {
  for (let i = 0; i < this.length; i++) {
    const el = this[i];
    if (callback(el, i)) {
      return el;
    }
    continue;
  }
  return undefined;
};
console.log(arr.customFind(el => el % 5 === 0));

ผลลัพธ์

15

คำอธิบายเพิ่มเติม

นี่คือการ implement polyfill สำหรับ Array.prototype.find() การแก้โปรโตไทพ์ในตัว (monkey patching) ไม่แนะนำใน production ควรใช้ฟังก์ชัน standalone หรือ utility library แทน