遍历JavaScript数组及性能

2018-07-12  本文已影响0人  前端开发爱好者

JavaScript数组常用的遍历方式有以下四种,

基本循环语句

function for_fun(arr){
    var length=arr.length;
    console.time("for")
    for(var i=0;i<length;i++){
        //todo
    }
    console.timeEnd("for")
}


function do_while_fun(arr){
    var i=0;
    console.time("do_while_fun")
    do{
        i++;
        //todo
    }while(arr[i]!==undefined)
    console.timeEnd("do_while_fun")
}

function while_fun(arr){
    var i=0;
    console.time("while_fun")
    while(arr[i]!==undefined){
        i++;
        //todo
    }
    console.timeEnd("while_fun")
}

数组的方法

function forEach_fun(arr){
    console.time("forEach")
    arr.forEach(function(value){
        //todo
    })
    console.timeEnd("forEach")
}

function map_fun(arr){
    console.time("map")
    arr.map(function(value){
        //todo
    })
    console.timeEnd("map")
}

es6新方法

function forof_fun(arr){
    console.time("forof")
    for(let value of arr){
        //todo
    }
    console.timeEnd("forof")
}

其他

for...in 是用于遍历对象的属性方法,通常不用于数组。

总结

数组的几种遍历方法中,其中循环语句的遍历运行速度较快,数组的遍历方法forEach不能在中途跳出循环,es6的for of循环弥补了forEach的缺陷,是比较好的选择。数组的map方法通常用来在当前数组的基础上返回一个新的数组。

测试运行速度

创建下面代码,创建数组对其进行遍历。遍历过程中不做任何操作,函数实现代码如上

var arr=[];
for(var i=0;i<1000000;i++){
    arr.push(Math.random())
}

for_fun(arr);
do_while_fun(arr);
while_fun(arr);

forEach_fun(arr);
map_fun(arr);

forof_fun(arr);

运行结果如下所示:


2018-07-12_174345.png
上一篇 下一篇

猜你喜欢

热点阅读