Một cách ngây thơ sẽ làm điều này nếu bạn đã thử nghiệm trên Chrome:
NodeList.prototype.forEach = Array.prototype.forEach;
này hoạt động. Trên Webkit. Nó không có trên Firefox. Bởi vì FF trả về một HTMLCollection ...
Các nhất qua trình duyệt cách tôi đã tìm thấy:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
Nó không làm việc trên IE8 và giảm mặc dù, bởi vì họ nghẹt thở khi thêm thuộc tính để lưu trữ đối tượng nguyên mẫu.
Danh mục đầy đủ:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.map = HTMLCollection.prototype.map = Array.prototype.map;
NodeList.prototype.filter = HTMLCollection.prototype.filter = Array.prototype.filter;
NodeList.prototype.reduce = HTMLCollection.prototype.reduce = Array.prototype.reduce;
NodeList.prototype.reduceRight = HTMLCollection.prototype.reduceRight = Array.prototype.reduceRight;
NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;
NodeList.prototype.some = HTMLCollection.prototype.some = Array.prototype.some;
Hoặc, để làm hài lòng Bergi thân yêu của chúng tôi (và cũng vì nó là sạch):
['forEach', 'map', 'filter', 'reduce', 'reduceRight', 'every', 'some'].forEach(
function(p) {
NodeList.prototype[p] = HTMLCollection.prototype[p] = Array.prototype[p];
});
Xét liên kết đến perfectionkills, nó chủ yếu là không thích hợp đó. Vấn đề là DOM hầu như không hoạt động giống nhau trên các trình duyệt khi mở rộng. Sửa đổi này là lành mạnh trong tất cả các trình duyệt ngoại trừ IE < = 8.
Nguồn
2012-12-19 17:00:00
Tại sao mọi người phân bổ mảng ('[]') thay vì sử dụng 'Array.prototype.forEach'? –