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

forEach() 是JS遍历数组的方法

复制代码

var arr=[1,2,3];
arr.forEach(function(val,index,arr){
// var 为数组中当前的值
// index 为当前值得下标
// arr 为原数组
arr[index] = 2*val;
})

console.log(arr); //结果:修改了原来数组,为每个数乘以2

复制代码

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
复制代码

点我

数组元素总和:

复制代码

注意: forEach() 对于空数组是不会执行回调函数的。

在jquery中,遍历对象和数组,经常会用到 ( ) . e a c h 和 ().each和 ().each.each(),两个方法。两个方法是有区别的。

( ) . e a c h : 在 d o m 处 理 上 面 用 的 较 多 。 如 果 页 面 有 多 个 i n p u t 标 签 类 型 为 c h e c k b o x , 对 于 这 时 用 ().each:在dom处理上面用的较多。如果页面有多个input标签类型为checkbox,对于这时用 ().eachdominputcheckbox().each来处理多个checkbook,例如:

KaTeX parse error: Expected '}', got 'EOF' at end of input: …unction(i){ if((this).attr(‘checked’)==true)
{
//一些操作代码

}

回调函数是可以传递参数,i就为遍历的索引。

$.each() :遍历一个数组

$.each([{“name”:“limeng”,“email”:“xfjylimeng”},{“name”:“hehe”,“email”:“xfjylimeng”},function(i,n)
{
alert(“索引:"+i,“对应值为:”+n.name);
});

参数i为遍历索引值,n为当前的遍历对象.

var arr1 = [ “one”, “two”, “three”, “four”, “five” ];
$.each(arr1, function(){
alert(this);
});
输出:one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
输出:1 2 3 4 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值