数组中的each 和 jquery 中的 each

    数组的实例上都有一个叫做 forEach 的方法,这个方法定义在 Array.prototype 上,所以数组的所有实例都可以使用 forEach 这个方法。 forEach 方法的语法结构如下:  

1 var ary = [1, 2, 3, 4, 5, 5, 6, 8, 9];
2 ary.forEach(function(index, item) {
3     // 这个函数一共会执行 ary.length 次
4     // index 当前数组的索引
5     // item 当前索引对应的哪项
6     // thisArg 当函数执行的时候,函数里面的 this 关键字
7 }, thisArg);

  forEach 方法的兼容程度是 IE9+,对于 IE8 浏览器,我们需要做兼容性处理,所以采用惰性函数的思想,对 forEach 方法做一个简单的处理,代码如下:

Array.prototype.forEach = (function() {
  //当对于支持 forEach 方法的浏览器,使用数组本身自带的方法
if (this.forEach) { return function(fn, thisArg) { thisArg = thisArg || window; fn.call(thisArg, index, item); } }
  //对于不支持 forEach 的浏览器,用自定义的方法重写数组类原型上的 forEach 方法
return function(fn, thisArg) { for (var i = 0, len = this.lenght; i < len; i++) { thisArg = thisArg || window; fn.call(thisArg, index, item); } } })();

 用过 jQuery 的朋友会发现,jQuery 中有 each 这个方法,一个是定义在 $.each 上,另一个是定义在 jQuery 的实例上。

 关于 $.each 这个方法,它的使用模式如下:

    $.each(需要遍历的对象/需要被遍历的数组,回调函数[可选的,参数是 index, item]);

    回调函数中的 item 就是当前被遍历到的项,如果传递进去的对象是 jquery 对象,item 是 dom 对象,而且函数中的 this 关键字指向这个 dom 对象;

    回调函数中如果传递进去的是数组,item 就是当前数组中的 index 对应的当前项,this 关键字指向当前项;

   函数执行的返回结果就是当前操作的参数。

  我们可以参见实例代码:

  实例代码1:$.each 操作数组   

//操作数组
var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var res =$.each(ary, function(index, item) {
    // do somthing
    console.log(index, item);
});
console.log(res ===ary);

   实例2: $.each 操作jQuery 对象

// 操作 jquery 对象
$.each($('p'),function(index,item) {
    console.log(this==item,index,item);
})

     挂载 $ 这个美元符号上的方法是 jQuery 上的工具方法, 通过 $(selector) 生成的 jQuery 对象上也有一个 each 方法,方法的使用参见 jquery api

$('p').each(function(index, item) {
    console.log(index + 1 + ":" + item.className);
});

   但是好像这个方法并没有太大的实际用处的样子。

   

posted @ 2015-09-18 17:20  张小喵  阅读(288)  评论(0编辑  收藏  举报