3 ms·
function aeach (fn, a) { return Array.prototype.forEach.call(a, fn) } Does this win anything over using forEach directly?
by TekMol 8y ago
function aeach (fn, a) { return Array.prototype.forEach.call(a, fn) }
Does this win anything over using forEach directly?
- tthisk 8y agoThis function could be used to iterate over the `arguments` array like object, but I do not think it is used for that purpose here.
- boomlinde 8y agoIt's used to iterate over HTMLCollection objects here.
- braythwayt 8y agoA lot of things like this will work on both arrays (thta have a .forEach method) and things that behave enough like arrays such that Array.prototype.forEach works for them. The downside of this approach (if you subscribe to the ideology of OO) is that if you make something completely unlike an array internally, like a linked list, you can’t use this function on it. Whereas, if you wrote a .forEach method for it, you could use it interchangeably with arrays anywhere the code calls .forEach. Without trying it, I’ll guess that this is used on the arguments magic parameter. It’s notorious for being array-like but not an array.
- Flenser 8y agoDOM functions like getElementsByClassName return a nodelist, which as you say behaves like an array.
- deleted 8y ago[deleted]
- TheAceOfHearts 8y agoThis works with array-like objects which aren't arrays. It's important if you want to support older browsers which don't implement NodeList.forEach(). Well, it's really just for old IE. If you're targeting modern browsers this is no longer an issue, as they all support NodeList.forEach(). It's worth noting that many DOM APIs return live collections, so depending on what you're doing you might want to clone it first. Luckily now with ES2015 you can use Array.from(list) or just [...list].