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

随机推荐

  1. STL--sort源码分析

    SGI STL sort源码 temlate <class RandowAccessIterator> inline void sort(RandowAccessIterator firs ...

  2. java hashmap的一些分析记录

    最近朋友去面试被问了些hashmap相关的问题,hashmap的初始容量啊,什么操作最耗时等,之前看过hashmap的源码,正好这里也在总结下. 主要围绕下面几个点: HashMap是由数组+链表(j ...

  3. 05mycat父子表

    表连接的难题在mycat中是不允许跨分片做表连接查询的 创建t_orders表 create table t_orders( id int PRIMARY key, customer_id int n ...

  4. C#多条件查出来的多个DataSet,然后循环将数据整合

    private List<string> barList;        public List<string> BarList        {            get ...

  5. SQL语句50题

    -- 一.创建教学系统的数据库,表,以及数据 --student(sno,sname,sage,ssex) 学生表--course(cno,cname,tno) 课程表--sc(sno,cno,sco ...

  6. python的pandas库学习笔记

    导入: import pandas as pd from pandas import Series,DataFrame 1.两个主要数据结构:Series和DataFrame (1)Series是一种 ...

  7. Windbg分析蓝屏Dump文件

    一.WinDbg是什么?它能做什么? WinDbg是在windows平台下,强大的用户态和内核态调试工具.它能够通过dmp文件轻松的定位到问题根源,可用于分析蓝屏.程序崩溃(IE崩溃)原因,是我们日常 ...

  8. C++智能指针剖析(上)std::auto_ptr与boost::scoped_ptr

    1. 引入 C++语言中的动态内存分配没有自动回收机制,动态开辟的空间需要用户自己来维护,在出函数作用域或者程序正常退出前必须释放掉. 即程序员每次 new 出来的内存都要手动 delete,否则会造 ...

  9. AES CBC PKCS7 C# C++

    c++算法见:https://blog.csdn.net/csdn49532/article/details/50686222 c#:https://gitee.com/koastal/codes/6 ...

  10. React知识杂烩(持续更新)

    每隔半年不看官方文档,你就会不认识React了