Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> [].slice.call( document.querySelectorAll('.foo'), function(){

When do you need to do that?



querySelectorAll returns a NodeList instead of a real array, so you can't call things like `.forEach` on the result. `[].slice.call(x)` turns x into an array, so that becomes

    [].slice.call(document.querySelectorAll(...)).forEach(function () {})
Because a lot of array methods are "generic", i.e. operate on array-like objects instead of just arrays, that can be "compacted" to

    [].forEach.call(document.querySelectorAll(...), function () {})
but neither are very nice.


Probably meant to be

    [].slice.call(document.querySelectorAll('.foo')).forEach(...
It "casts" the NodeList which is "Array-like" to a proper Array, which has forEach, map and other useful methods in its prototype.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: