JS中的遍历方式

98 阅读1分钟

js.png

数组遍历:

1.普通的for循环遍历,经常使用的数组遍历的方法

  let arr = [1, 3, 4, 5, 6, 7];
    for (let i = 0; i < arr.length; i++) {
      console.log(arr[i]);
    }

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

   let arr = [1, 3, 4, 5, 6, 7];
    for (let j = 0, len = arr.length; j < len; j++) {
      console.log(arr[j]);
    }

3.forEach,ES5推出的,数组自带的循环,主要功能就是遍历数组,实现性能比for还弱性

   let arr = [1, 3, 4, 5, 6, 7];
    arr.forEach((value, index) => {
      console.log('forEach遍历的:' + index + '---' + value);
    });

总结:forEach这种方法有一个小缺陷,你不能使用break语句来进行中断循环,也不能使用return语句返回到最外层的函数的结果

4.map遍历:map即是-'映射' 的意思,用法和forEach相似

    let arr = [1, 3, 4, 5, 6, 7];
    arr.map((value, index) => {
      console.log('map的遍历方式' + index + '--' + value);
    });

结论: map遍历支持使用return语句,支持return的返回值

    let list = arr.map(function (value, index) {
      console.log(value);
      return value * value;
    });
    console.log(list);

总结:forEach和map都是ECMA5新增的数组方法,所以IE9 (IE6 7 8 ) 一下的版本都不支持

对象遍历:

for-in遍历:
for-in是为了遍历对象而设计的,不适用于遍历数组。
遍历数组的缺点
1.数组的下标index值是数字
2.for-in遍历的index值是'0','1','2','3'...等,这些字符串

 let arr = [1, 3, 4, 5, 6, 7];
 for (let index in arr){
     console.log(arr[index]);
     console.log(index);
}