zoukankan      html  css  js  c++  java
  • javascript 数组遍历方法对比

    for方法

    for (var index = 0; index < myArray.length; index++) {
      console.log(myArray[index]);
    }
    

    优缺点:

    这种写法比较麻烦

    forEach方法

    myArray.forEach(function (value) {
      console.log(value);
    });
    

    优缺点:

    无法中途跳出forEach循环,break命令或return命令都不能奏效。

    for...in方法

    for (var index in myArray) {
      console.log(myArray[index]);
    }
    

    优缺点:

    • 数组的键名是数字,但是for...in循环是以字符串作为键名“0”、“1”、“2”等等。
    • for...in循环不仅遍历数字键名,还会遍历手动添加的其他键,甚至包括原型链上的键。
    • 某些情况下,for...in循环会以任意顺序遍历键名。

    总之,for...in循环主要是为遍历对象而设计的,不适用于遍历数组。

    for...of方法

    for (let value of myArray) {
      console.log(value);
    }
    

    优缺点:

    • 有着同for...in一样的简洁语法,但是没有for...in那些缺点。
    • 不同于forEach方法,它可以与break、continue和return配合使用。
    • 提供了遍历所有数据结构的统一操作接口。

    参考原文链接

  • 相关阅读:
    gj10 python socket编程
    自定义Git
    使用GitHub
    标签管理之操作标签
    标签管理之创建标签
    标签管理
    git分支管理之多人协作
    git分支管理之Feature分支
    git分支管理之Bug分支
    git分支管理之分支管理策略
  • 原文地址:https://www.cnblogs.com/xmyun/p/10025201.html
Copyright © 2011-2022 走看看