Un modo semplice sarebbe quello di fare questo se testato su Chrome:
NodeList.prototype.forEach = Array.prototype.forEach;
Questo funziona. Su Webkit. Tuttavia non funziona su Firefox. Perché FF restituisce un HTMLCollection ...
Il modo più cross-browser che ho trovato:
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
Non funziona su IE8 e abbassare però, perché soffocare quando si aggiungono le proprietà per ospitare gli oggetti prototipi.
Lista completa:
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;
Oppure, per soddisfare i nostri cari Bergi (e anche perché è più pulito):
['forEach', 'map', 'filter', 'reduce', 'reduceRight', 'every', 'some'].forEach(
function(p) {
NodeList.prototype[p] = HTMLCollection.prototype[p] = Array.prototype[p];
});
Considerando il link al perfectionkills, è per lo più irrilevante lì. Il problema è che il DOM non si comporta per lo più sui browser quando è esteso. Questa modifica è normale in tutti i browser eccetto IE < = 8.
fonte
2012-12-19 17:00:00
Perché tutti allocare un array ('[]') invece di utilizzare 'Array.prototype.forEach'? –