2 ms·
> [].slice.call( document.querySelectorAll('.foo'), function(){ When do you need to do that?
by Kiro 11y ago
> [].slice.call( document.querySelectorAll('.foo'), function(){
When do you need to do that?
- renekooi 11y agoquerySelectorAll 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.
- egeozcan 11y agoProbably 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.