0
forEach
/ slice.Call()
/ [].slice()
Can someone give me a brief explanation of these methods, and when I can use them?
0
forEach
/ slice.Call()
/ [].slice()
Can someone give me a brief explanation of these methods, and when I can use them?
4
You should note that jQuery methods are for applying to jQuery collections and not native arrays/objects.
.forEach()
The .forEach(el, index)
is not a jQuery method. It is rather a native Javascript method introduced in version ES5. The jQuery correspondent for this method is the .each(index, el)
which has the callback arguments reversed, and passes the el
as a context to callback.
This method (both the native version and the jQuery version) are iterators. They are used to traverse an jQuery array or 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()
in itself, serves to create copies of pieces of an array/collection.
.call()
or [].slice.call()
?The methods I described above (and many others as well) have an internal method which is the .call()
. This method allows calling the slice
, forEach
or another passing as context the first argument that this method receives. Remember I mentioned that the .forEach
jQuery’s name is .each
and passes the collection element as context? ie the this
inside the callback... yeah, what jQuery does is call .each.call(el, etc...
.
The idea here is to call a function or method controlling the context in which it will be run.
Use [].slice.call
is basically the same as Array.prototype.slice.call
, but shorter :) And allows converting Lists into arrays. Lists are not arrays, but can be converted into arrays. An example of a List is the result of document.querySelectorAll('div');
, who do not have a method .forEach
but can be iterated if used so:
var divs = [].slice.call(document.querySelectorAll('div'));
// e depois:
divs.forEach(function(el){
// fazer algo sobre o elemento <div> a ser iterado
});
Browser other questions tagged javascript jquery
You are not signed in. Login or sign up in order to post.
Do you already have the methods and want a problem? It would be more interesting if you bring a problem for us to guide you about which methods apply. Anyway, take a look at MDN.
– Pablo Almeida
I hope I have shed some light on your question. Perhaps new questions arise from this explanation. Try to separate them and if you can’t find an answer put a new per4gunta, more specific than this :)
– Sergio
Pedro here can also accept the answer, or ask for clarification if it is not clear. If you don’t know how to do it take a look here: http://meta.pt.stackoverflow.com/a/1079/129
– Sergio