JQuery数组遍历 您所在的位置:网站首页 jquery循环添加数组 JQuery数组遍历

JQuery数组遍历

2024-06-26 18:24| 来源: 网络整理| 查看: 265

【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 = "" + data.county + ""; $("#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

结果如下:

这里写图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有