OK jQuery experts : So .. I’m coming from a Prototype background.
I do the following code all the time (or some similar variation):
MyObject.prototype.someFunction = function()
{
var myArray = ["a","b","c"];
myArray.each(function(arrayEntry)
{
this.printPart(arrayEntry);
}, this);
}
MyObject.prototype.printPart = function(part)
{
console.log(part);
}
I’m looking through the jQuery docs — I don’t see how to do this.
Is this possible?
In particular, I’m interested in:
- Iterating through javascript arrays (objects would be nice too).
- Maintaining scope. Notice the final “this” parameter to the each function.
You’re looking for
$.each(array, function(i, element) { ... })That also handles objects, in which case you get
(key, value)in the arguments.edit — sadly there’s nothing like Prototype’s
inject, and I really miss that a lot. But there’smapin jQuery and that’s kind-of likecollectin Prototype.edit again — As @Nick points out in his comment, Prototype and jQuery disagree as to the best way to deal with handling “this”. Generally, jQuery invokes “handler” functions with “this” pointing to the obvious relevant object. Prototype is more hands-off as far as that goes.