代码之家  ›  专栏  ›  技术社区  ›  desau

Enumerating through a JS array in jQuery

  •  4
  • desau  · 技术社区  · 15 年前

    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?

    我特别感兴趣的是:

    • Iterating through javascript arrays (objects would be nice too).
    • Maintaining scope. Notice the final "this" parameter to the each function.
    2 回复  |  直到 15 年前
        1
  •  5
  •   Pointy    15 年前

    你在寻找 $.each(array, function(i, element) { ... })

    也处理对象,在这种情况下,您得到 (key, value) 在争论中。

    编辑 -遗憾的是没有什么像原型 inject 我真的很怀念。但是有 map 在jQuery中,有点像 collect 在原型中。

    再次编辑 -正如@nick在他的评论中指出的,原型和jquery对于处理“这个”的最佳方式存在分歧。通常,jquery调用“handler”函数,其中“this”指向明显相关的对象。原型更容易上手。

        2
  •  1
  •   Anurag    15 年前

    您不必在jQuery中做所有的事情。只添加一个 forEach 方法,如果它不存在,则使用该方法。很好,EcmaScript第5版采用了它作为标准(受到原型每种方法的启发),但并不是所有的浏览器都有它。下面是一个规范实现,您可以使用它,直到所有浏览器都拥有它。( taken from MDC ):

    编辑 :Chrome、Safari、Firefox和Opera的最新版本已经支持这一点。无法访问IE,抱歉。

    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);
        }
      };
    }
    

    然后使用你的代码原样(改变) each 前额 ):

    var myArray = ["a","b","c"];
    
    myArray.forEach(function(arrayEntry) {
        this.printPart(arrayEntry);
    }, this);