JS数组的遍历

一、数组遍历

1、普通for循环,经常用的数组遍历

var arr=['a',1,'b','c',12];
    for ( var i = 0; i <arr.length; i++){
        console.log(arr[i]);
    }

2、优化版for循环:使用变量,将长度缓存起来,避免重复获取长度,数组很大时优化效果明显

for(var j = 0,len = arr.length; j < len; j++){
        console.log(arr[j]);
    }

3、弱化版for循环:这种方法其实严格上也属于for循环,只不过是没有使用length判断,而使用变量本身判断实际上,这种方法的性能要远远小于普通for循环

for(j = 0; arr[j]!=null; j++) {
        console.log(arr[j]);
    }

4、forEach循环:数组自带的循环,不支持return语句返回到外层函数。三个参数依次是数组元素、索引、数组本身

arr.forEach(function(value,index,array){
        console.log('第'+index+'个:'+value);
    })

5、map遍历:map即是 “映射”的意思 用法与 forEach 相似

arr.map(function(value,index){
        console.log('第'+index+'个:'+value);
    });

        map遍历支持使用return语句,支持return返回值,返回值是一个新的数组

var temp=arr.map(function(val,index){
        console.log(val);
        return val*val
    });
    console.log(temp);

6、for-in遍历:听说它的效率是最低的。for-in是为遍历对象而设计的,不适用于遍历数组

for (var index in arr){
        console.log('第'+index+'个:'+arr[index]);
    }

7、for-of遍历

1)for-of这个方法避开了for-in循环的所有缺陷
2)与forEach()不同的是,它可以正确响应break、continue和return语句
3)for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象。
4)for-of循环也支持字符串遍历
for( let i of arr){
        console.log(i);
    }

8、jQuery的$.each()方法:它接受两个参数,分别指代数组索引和数组元素

$.each(arr,function(index,value){
        console.log(index+": "+value)
    });

猜你喜欢

转载自blog.csdn.net/qq_33459369/article/details/81808954