Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
for(j = 0; j < arr.length; j++) {
}
说明:性能很高,但是仍可以优化。
for(j = 0,len=arr.length; j < len; j++) {
}
说明:性能最高,使用临时变量,将长度缓存起来,避免重复获取数组长度,数组长度越大时优化效果越明显。
for(j = 0; arr[j]!=null; j++) {
}
说明:严格上也属于for循环,只不过是没有使用length判断,而使用变量本身判断。
arr.forEach(function(value,index,array){//value:当前项 index:索引 array:原始数组
});
说明:
在IE6-8下都不兼容。
数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;
示例:

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]; 通过数组索引改变了原数组

Array.prototype.forEach.call(arr,function(el){
});
说明:在IE6-8下都不兼容。
for(j in arr) {
}
说明:效率最低。
arr.map(function(value,index,array){//value:当前项 index:索引 array:原始数组
});
说明:效率低,比不上foreach
区别: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]; 原数组并未发生变化

for(let value of arr) {
});
说明:是es6里面用到的,性能要好于forin,但仍然比不上普通for循环。
一般意义上的效率:优化版for循环>普通for循环>弱化版for循环>……>forin循环|foreach变种
$.each(array,function(index,value){
})
示例:
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
})
在dom处理上用的比较多,如果一个html页面上面有多个checkbox,这时用$().each来处理checkbox
示例
$("input[type='checkbox']").each(function(index,item){
$(this).attr("checked",true);
});