前端有道 前端有道
导航
算法
开发
  • Git

    • Git导读
  • 收藏夹 (opens new window)
  • 工具库 (opens new window)
  • netlify Vuepress (opens new window)
  • vercel Vuepress (opens new window)
  • Vuepress2.0 (opens new window)
  • netlify Vuepress2.0 (opens new window)
留言区
娱乐
关于
  • 时间轴
  • 标签
  • 分类

星野

给岁月以文明
导航
算法
开发
  • Git

    • Git导读
  • 收藏夹 (opens new window)
  • 工具库 (opens new window)
  • netlify Vuepress (opens new window)
  • vercel Vuepress (opens new window)
  • Vuepress2.0 (opens new window)
  • netlify Vuepress2.0 (opens new window)
留言区
娱乐
关于
  • 时间轴
  • 标签
  • 分类
  • 基础知识

    • JS中数组有多少种遍历的方法
      • for循环
      • forEach遍历
      • forIn循环
      • map遍历
      • forof遍历(ES6)
      • find
  • 工程化

  • 组件库

  • CSS

  • ES6-ES12

  • JavaScript

  • Vue2

  • Vue3

  • webpack

  • 浏览器

  • 开发
  • 基础知识
星野
2022-03-16
0
目录

JS中数组有多少种遍历的方法

# ECMAScript中数组有多少种遍历的方法

demo数组

const list = [7, 5, 2, 3, 5]

# for循环

简单实用的一种,性能不错。可以用break、continue中断循环操作。

语法

for (初始化表达式; 条件; 递增表达式) {
  语句
}
  • 初始化表达式(initialize):确定循环变量的初始值,只在循环开始时执行一次。
  • 条件表达式(test):每轮循环开始时,都要执行这个条件表达式,只有值为真,才继续进行循环。
  • 递增表达式(increment):每轮循环的最后一个操作,通常用来递增循环变量。

执行的顺序为:

  • 第一次循环,即初始化循环 : 初始化表达式 --> 条件表达式 --> 语句 --> 递增表达式
  • 下次的循环: 条件表达式 --> 语句 --> 递增表达式

示例

for (let index = 0; index < array.length; index++) {
    const element = array[index];
}

优化for循环

使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组长度多时优化效果比较明显。

for (let index = 0,len = array.length; index < len; index++) {
    const element = array[index];
}

# forEach遍历

  • 没有返回值,可以改变原数组。
  • 没有中断操作,意味着不能用break、continue,性能弱于普通for循环。
array.forEach(element => {
       
});

# forIn循环

这个循环很常用,但实际上,经分析测试,在众多的循环遍历方式中,它的效率是最低的。

其实这个API本身就不是给数组遍历使用的。

for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
        const element = object[key];
        array.forEach(element => {
            
        });
    }
}

# map遍历

map和forEach使用方法类似,性能略弱于forEach,区别在于map返回值会产生一个新数组。

array.map(element => {
       
});

# forof遍历(ES6)

# find

性能分析 有兴趣的同学可以参考这个demoJS中几种常用数组遍历性能分析工具 (opens new window)

# 参考

  • https://wangdoc.com/javascript/basic/grammar.html#for-%E5%BE%AA%E7%8E%AF
  • https://coding.imooc.com/learn/list/389.html
  • https://dailc.github.io/2016/11/25/baseKnowlenge_javascript_jsarrayGoThrough
#基础知识
上次更新: 2022/05/09, 06:48:29
正则速查表

正则速查表→

最近更新
01
图解Git
05-10
02
关于 - 网站错误反馈
05-10
03
关于 - 赞赏❤️的用途
05-10
更多文章>
加入前端有道交流群 | Copyright © 2018-2025 星野 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式