I saw this script somewhere else, and it will check every single checkboxes:
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){
el.checked=true;
}
);
I know how to use forEach:
[0,1,2].forEach(function(num){
console.log(num);
});
//0
//1
//2
But now, it is [].forEach, and there is nothing inside. So why does it still work? Why can’t I do this instead?
document.querySelectorAll('input[type="checkbox"]').forEach(function(el){
el.checked=true;
}
);
JavaScript has first-class functions; that is, they’re treated like objects, and can have their own properties and methods. The built in
Function.callmethod takes athisparameter for the function as its first argument, and the rest of the arguments are passed to the function itself. The array[]is not used, except as a means to access the (less concise, so less used)Array.prototype.forEachmethod.It’s basically a rebinding of
Array.forEachfor use on something that is not an array, in this case aNodeList. IfNodeLists offered aforEachmethod, then it would be equivalent to, and you may read it as, this:So, a little more in depth.
callwill execute a function with a different context.forEachiterates over the context and calls the function it is passed as its argument. So asomeFunc.call(thisArg, otherArg)will be executed as if it were in the context ofthisArg, likethisArg.someFunc(otherArg). Here’s the simplest example:apply()works the same way, but you pass an array of arguments as the second argument.