Giả sử chúng ta có mảng số và đã thêm các phần tử. Bạn cần cách đơn giản để xóa một phần tử cụ thể khỏi mảng.
Điều chúng ta tìm kiếm là:
array.remove(number);
Chỉ sử dụng JavaScript thuần túy, không dùng framework.
Ví dụ
Mã thực hiện như sau:
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);
};
};
// nếu có phần tử bị xóa trả về true, ngược lại false
if(this.length !== length){
return true;
};
return false;
};
Array.prototype.removeInstances = removeInstances;
console.log(arr.removeInstances(5));
console.log(arr);
Kết quả
Kết quả trong console sẽ là:
true [ 2, 9, 1, 8 ]