遍历

ES有新的遍历方式 for of

const fruits = ["apple", "banana", "orange", "mango"]
fruits.describe = "this is all describe"

Array.prototype.firstName = function() {
    return this[0]
}

常用遍历方式

  1. for循环
    写法比较繁琐

    for (let index = 0; index < fruits.length; index++) {
        if(fruits[index] == "banana") {
    continue;
    }
    console.log("for循环" + fruits[index])
    }
    /*
    for循环apple
    for循环banana
    for循环orange
    for循环mango
    */
  2. for each

    可以使用箭头函数 写法便捷 但是不能使用continue 和 break

    fruits.forEach(fruit => {
    // if(fruit == "banana") {
    // continue;
    // }
    console.log("for each "+fruit)
    });
    /*
    for each apple
    for each banana
    for each orange
    for each mango
    */
  3. for in

    forin 遍历获取的是key 需要额外取值value
    forin不仅仅可以遍历可迭代对象
    forin遍历可以获取对象的原型方法和对象方法、属性

    for (const key in fruits) {
        if(fruits[key] == "banana") {
    continue;
    }
    console.log("for in key "+ key+ " value " + fruits[key])
    }
    /*
    for in key 0 value apple
    for in key 2 value orange
    for in key 3 value mango
    for in key describe value this is all describe
    for in key firstName value function() {
    return this[0]
    }
    */

    forin遍历不可迭代对象

    const fankai = {
        name: "fankai",
    age: 26
    }
    for (const value in fankai) {
    console.log(value)
    }
  4. for of

    遍历可迭代对象

    for (const fruit of fruits) {
        if(fruit == "banana") {
    continue;
    }
    console.log("for of "+ fruit)
    }
    /**
    * for of apple
    * for of orange
    * for of mango
    */

for of

只能遍历可迭代对象
可迭代对象就是部署了iterable接口 或者定义了Symbol.iterator方法的数据结构。
js内置了一些带遍历器接口的数据结构,例如Array、map

iterable接口 内置了next方法,调用该方法返回对象,该对象包含值value,以及是否遍历结束的标识done,value中包含了当前的索引以及索引对应的值

entries()可以获取包含数组的键值对

//entries() 获取数组的可迭代对象 该对象包含数组的键值对(key/value)
for (let [index, fruit] of fruits.entries()) {
    console.log(index, fruit)
}

for of 常用实例

for of循环遍历除了可以遍历数组外 还经常用于其他地方:

  1. 遍历方法参数arguments

    function sum() {
        for (const variable of arguments) {
    console.log(variable)
    }
    }
  2. 遍历字符串

    for (const char of "object") {
        console.log(char)
    }
  3. 遍历DOM元素

    const lis = document.querySelectorAll("li")
    for (const li of lis) {
    }