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

การสร้างฟังก์ชัน customIncludes คล้าย Array.prototype.includes() ใน JavaScript


ปัญหา

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

ตัวอย่าง

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

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const num = 6;
Array.prototype.customIncludes = function(num){
  for(let i = 0; i < this.length; i++){
    const el = this[i];
    if(num === el){
      return true;
    };
  };
  return false;
};
console.log(arr.customIncludes(num));

ผลลัพธ์

true