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


1.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() 方法用于调用数组的每个元素,并将元素传递给回调函数。

<button onclick="numbers.forEach(myFunction)">点我</button>
<p>数组元素总和:<span id="demo"></span></p>

<script>
var sum = 0;
var numbers = [65, 44, 12, 4];

function myFunction(item) {
    sum += item;
    demo.innerHTML = sum;
}
</script>

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


 

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

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

$("input[name='ch']").each(function(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

参考链接:http://www.frontopen.com/1394.html   https://www.cnblogs.com/longailong/p/6409172.html

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM