开发者

Enumerating through a JS array in jQuery

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.pr开发者_运维知识库intPart = 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's map in jQuery and that's kind-of like collect in 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.


You don't necessarily have to do everything in jQuery. Just add a forEach method if it doesn't already exist, and use that instead. It was so good that ECMAScript 5th ed. adopted it as a standard (inspired by Prototype's each method), but not all browsers have it yet :). Here's an implementation by the spec that you can use until all browsers have it natively (taken from MDC):

Edit: Latest versions of Chrome, Safari, Firefox, and Opera already support this. No IE access, sorry.

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

Then use your code as it is (change each to forEach):

var myArray = ["a","b","c"];

myArray.forEach(function(arrayEntry) {
    this.printPart(arrayEntry);
}, this);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜