Mở rộng Array.prototype thêm phương thức pushAtFalsy(element): chèn element vào vị trí falsy đầu tiên (null, undefined, "", 0, false, NaN, hole) nhưng bỏ qua số 0. Nếu không có vị trí falsy, push vào cuối.
Ví dụ
Mảng: [13, 34, 65, null, 64, false, 65, 14, undefined, 0, , 5, , 6, ,85, ,334]
Chèn lần lượt: 4, 42, 424, 4242, 42424, 424242, 4242424
Giải pháp
Mã triển khai:
const arr = [13, 34, 65, null, 64, false, 65, 14, undefined, 0, , 5, , 6, ,85, ,334];
const pushAtFalsy = function(element) {
for (let index = 0; index < this.length; index++) {
// Falsy nhưng KHÔNG phải number (giữ 0)
if (!this[index] && typeof this[index] !== 'number') {
this.splice(index, 1, element);
return;
}
}
this.push(element); // Không tìm thấy falsy slot
};
Array.prototype.pushAtFalsy = pushAtFalsy;
arr.pushAtFalsy(4);
arr.pushAtFalsy(42);
arr.pushAtFalsy(424);
arr.pushAtFalsy(4242);
arr.pushAtFalsy(42424);
arr.pushAtFalsy(424242);
arr.pushAtFalsy(4242424);
console.log(arr);
Kết quả
Đầu ra trong console:
[13, 34, 65, 4, 64, 42, 65, 14, 424, 0, 4242, 5, 42424, 6, 424242, 85, 4242424, 334]
Cảnh báo: Sửa đổi Array.prototype không khuyến khích trong production.