JQuery数组遍历 - $.each(),$().each()和forEach()

【1】$().each(function(){})-DOM处理

对于这个方法,在dom处理上面用的较多

如果页面有多个input标签类型为checkbox,对于这时用$().each来处理多个checkbook,例如:

$("input[name='ch']").each(function(index){
	if($(this).attr("checked")==true){
		//一些操作代码
	}
}

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


【2】$.each(parentData,function(index,childData){})

对于这个方法,在集合数据处理上面用的较多

参数描述
function(index,element)必需。为每个匹配元素规定运行的函数。index:选择器的index位置;element:当前的元素(也可使用‘this’选择器)

遍历JSON

var json=[{"name":"limeng","email":"xfjylimeng"},{"name":"hehe","email":"fjylimeng"}]
$.each(json,function(index,data){
	alert("索引:"+index+","+"对应值为:"+data.name);
});

遍历MAP

var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
	alert(obj[key]);
});

遍历list

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

遍历JSON并取数据进行操作

$.each(countyJson, function(index, data) {
   if (data.parent == selValue) {
       var option = "<option value='" + data.id + "'>" + data.county + "</option>";
       $("#selDistrict").append(option);
   }
});

注意,此处的json为JS对象,若为字符串,使用JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';
 
$.each(JSON.parse(json), function(idx, obj) {
    alert(obj.tagName);
});
 
//or 
 
$.each($.parseJSON(json), function(idx, obj) {
    alert(obj.tagName);
});

【3】array.forEach()

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

是JS中遍历数组的,不能遍历对象,遍历对象用 for in,或者将对象转化为数组,用[].slice.call(jQuery实例对象);
foreach的回调函数function有三个参数,第一个是val为数组当前的值,第二个index为当前值的下标,第三个arr为原数组;
forEach()中没有返回值;

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

语法格式如下:

array.forEach(function(currentValue, index, arr), thisValue)

参数解析如下:

这里写图片描述

示例如下:

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

结果如下:

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值