原生js中的forEach和jQuery中的each方法的区别

ES5中的forEach()方法

forEach是ES5中的一个数组遍历函数,是js原生支持的遍历方法。
语法:

数组.forEach(function(每一项内容,序号){
    
    
})

例如:

// IE8 不支持
var array1 = ['abc','d','ddd'];
array1.forEach(function (item,index){
    
    
    console.log(item);
});

jQuery中的each()方法

jQuery中的each()方法可以:
1、方便的遍历 jQuery 元素(伪数组)
2、可以在不兼容 forEach的低版本浏览器中使用 jQuery 的forEach方法

语法:

//普通数组
$.each(数组,function (序号,每一项内容){
    
    

});

//伪数组
$('div').each(function (序号,每一项内容){
    
    
  
})
`

例如:

var array2 = ['abc','d','ddd'];
$.each(array2,function (index,item){
    
    
    console.log(item);
});
$('div').each(function (index,item){
    
    
    console.log(item);
})

伪数组是对象,对象的原型链是Object.prototype,其中没有 forEach方法。
这里的 each 方法是 jQuery 提供的,这个 each方法 在jQuery的原型链中。

用 forEach()方法遍历jQuery元素

要想使用 forEach()方法遍历jQuery元素,需要先把伪数组转换为数组。

例如:

[].slice.call($('div')).forEach(function (item,index){
    
    
    console.log(item);
})

猜你喜欢

转载自blog.csdn.net/cake_eat/article/details/109003682
今日推荐