• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
不见花落
博客园    首页    新随笔    联系   管理    订阅  订阅
$.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

 

posted on 2019-03-13 15:33  不见花落  阅读(2994)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3