$.each()和$().each(),以及forEach()的用法

转自:http://maplebb.blog.51cto.com/2547849/1918563jquery



总结:forEach必须是数组才能用的遍历方法数组

         each是jquery提供给dom元素或选择器使用的遍历方法dom

         $.each则是数组或对象均可用的遍历方法
ide


1.forEach是js中遍历数组的方法,以下函数

var arr=[1,2,3,4];
arr.forEach(function(val,index,arr){//val为数组中当前的值,index为当前值的下表,arr为原数组
   arr[index]=2*val;
});
console.log(arr);//结果是修改了原数组,为每一个数乘以2

注意:forEach是 ES5 中数组 Array 内置的原生方法 IE9如下不支持this



2.$.each()是jquery中遍历数组对象的方法,以下spa

$.each( obj , function ( key ,val ) {
orm

} )对象

$.each( arr , function ( index , value ) {blog

} )

var arr=[1,2,3,4];
$.each(arr,function(i,n){
   alert("索引"+i+"对应的值"+n);
});



3.$().each()方法规定为每一个匹配元素规定运行的函数,以下:

$(selector).each(function(index,element){

        // index是遍历selector中的每一项时,当前项的索引,从0开头

       //  element是遍历selector中的每一项时,当前项dom元素

      //  若是有 return 返回 false 则终止(退出)循环

})

$(selector).each(function(){ $(this) 


    })

相关文章
相关标签/搜索