สมมุติว่าเรามีอาร์เรย์ของตัวเลขและเราเพิ่มองค์ประกอบเข้าไป คุณต้องคิดวิธีง่ายๆ ในการลบองค์ประกอบเฉพาะออกจากอาร์เรย์
ต่อไปนี้เป็นสิ่งที่เรากำลังมองหา -
array.remove(number);
เราต้องใช้จาวาสคริปต์หลัก ไม่อนุญาตให้ใช้เฟรมเวิร์ก
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const arr = [2, 5, 9, 1, 5, 8, 5];
const removeInstances = function(el){
const { length } = this;
for(let i = 0; i < this.length; ){
if(el !== this[i]){
i++;
continue;
}
else{
this.splice(i, 1);
};
};
// if any item is removed return true, false otherwise
if(this.length !== length){
return true;
};
return false;
};
Array.prototype.removeInstances = removeInstances;
console.log(arr.removeInstances(5));
console.log(arr); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
true [ 2, 9, 1, 8 ]