forEach
/ slice.Call()
/ [].slice()
Can anyone give me a brief explanation of these methods, and when can I use them?
forEach
/ slice.Call()
/ [].slice()
Can anyone give me a brief explanation of these methods, and when can I use them?
You should note that jQuery methods are for applying to jQuery collections rather than to native arrays / objects.
.forEach()
.forEach(el, index)
is not a jQuery method . It is rather a native method of JavaScript introduced in version ES5. The jQuery match for this method is .each(index, el)
that has the callback arguments reversed, and passes el
to it context to the callback.
This method (both the native and jQuery version) is iterators. They serve to traverse an array or jQuery collection.
.slice()
This method exists in jQuery and also in native JavaScript. Again they are similar and do the same thing, respectively in jQuery collections or native arrays.
The method .slice()
itself serves to create copies of pieces of an array / collection.
.call()
or [].slice.call()
? The methods I described above (and many others too) have an internal method that is .call()
. This method lets you call slice
, forEach
or other passing as context the first argument that this method receives. Do you remember that I mentioned that .forEach
of jQuery is called .each
and passes the collection element as context? I want to use jQuery to call the%
The idea here is to be able to call a function or method by controlling the context in which it will be run.
Using this
is basically the same as .each.call(el, etc...
, but shorter :) And allows you to convert Lists into arrays. Lists are not arrays, but can be converted into arrays. An example of a List is the result of [].slice.call
, which does not have a Array.prototype.slice.call
method but can be iterated if used like this:
var divs = [].slice.call(document.querySelectorAll('div'));
// e depois:
divs.forEach(function(el){
// fazer algo sobre o elemento <div> a ser iterado
});