arr[].forEach(function(value,index,array){
//do something
})
你不能使用break语句中断循环,也不能使用return语句返回到外层函数。
- 参数:value数组中的当前项,index当前项的索引,array原始数组;
- 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
- 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;
-
var arr = [12,23,24,42,1]; var res = arr.forEach(function (item,index,input) { input[index] = item*10; }) console.log(res);//-->undefined; console.log(ary);//-->[120,230,240,420,10]; 通过数组索引改变了原数组
arr[].map(function(value,index,array){
//do something
})
- 参数:value数组中的当前项,index当前项的索引,array原始数组;
- 区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
-
var arr = [12,23,24,42,1]; var res = arr.map(function (item,index,input) { return item*10; }) console.log(res);//-->[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改 console.log(ary);//-->[12,23,24,42,1]; 原数组并未发生变化
- 遍历一个数组通常用$.each()来处理
-
$.each(arr, function(index,value){
//do something
})
- 参数:arr要遍历的数组,index当前项的索引,value数组中的当前项
- 第1个和第2个参数正好和以上两个函数是相反的,注意不要记错了
-
var arr = [12,23,24,42,1]; $.each(arr, function (index,item) { console.log(index) // 0 1 2 3 4 console.log(item) // 12 23 24 42 1 })
$().each 在dom处理上面用的较多。如果页面有多个input标签类型为checkbox,对于这时用$().each来处理多个checkbook,例如:
-
$(“input[name=’ch’]”).each(function(i){ if($(this).attr(‘checked’)==true) { //一些操作代码 } //回调函数是可以传递参数,i就为遍历的索引。
for...in 语句用于对数组或者对象的属性进行循环操作。·
for ... in 循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。
- 简而言之,for-in是为普通对象设计的,你可以遍历得到字符串类型的键,因此不适用于数组遍历。
-
Tip:for-in循环应该用在非数组对象的遍历上,使用for-in进行循环也被称为“枚举”。
-
语法:
for (变量 in 对象) { 在此执行代码 }
for (var value of myArray) { console.log(value); }