一文完全弄懂 for forEach for-in for-of 的区别

基本语法

下面列出了这几个遍历语法规则:javascript

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

array.forEach(element => {
    // ...
})

for (const key in array) {
    // ...
}

for (const iterator of array) {
    // ...
}
复制代码

分状况讨论这几种写法的不一样

非数字的属性

在 JavaScript 中全部的数组都是对象,这意味着你能够给数组添加字符串属性:html

array = ['a', 'b', 'c']

array.test = 'testing'
console.log(array) // [ 'a', 'b', 'c', test: 'testing' ]
复制代码

若是打印,那么这个 test 也会被打印出来java

在浏览器中,使用 console.table(array) 打印这个数组能够看到,这个对象中 test 为 index,testing 为 value;其余数组项的 index 值均为数字编程

20190228105221.png

上述提到的几个遍历方法中只有 for-in 循环才可以打印出这个键值对:数组

for (const key in array) {
    console.log(array[key])
}
复制代码

实际应用的问题

一般状况下,不建议使用 for-in 来遍历数组,除非你知道这个数组对象中没有这样的属性浏览器

数组空项

假设要遍历的数组张这样:array = ['a', , 'c']异步

// a undefined c
for (let index = 0; index < array.length; index++) {
    const element = array[index]
    console.log(element) // 没有跳过空值
}

// a c
array.forEach(element => {
    console.log(element) // 跳过空值
})

// a c
for (const key in array) {
    console.log(array[key]) // 跳过空值
}

// a undefined c
for (const iterator of array) {
    console.log(iterator) // 没有跳过空值
}
复制代码

上面几个遍历方法,只有 forEach 和 for-in 遍历会跳过空值,值得注意的是,若是空值明确设置为 undefined 如 ['a', undefined, 'c'] 那么全部遍历方法都可以将 undefined 遍历出来async

实际应用的问题

在 JSON 中是不支持这样的空值的,若是在 parse 方法调用时传入的 JSON 字符串数据含有空值,会报错:异步编程

JSON.parse('["a", , "c"]')
// 因此建议使用 for-of 或 for 循环进行遍历,由于若是
复制代码
  • stringify 方法调用时,空值会被转为 null 非空值或 undefined
  • 正确的作法应该是保持 undefined,遍历使用 for-of 或 for 循环

建议使用 for-of函数

方法 this 指向的上下文

在 forEach 中须要传入一个函数,这个函数的 this 指向因语法形式而变化:

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

array.forEach(function (element) {
    console.log(this) // undefined
})

array.forEach(element => {
    console.log(this) // {}
})

for (const key in array) {
    console.log(this) // {}
}

for (const iterator of array) {
    console.log(this) // {}
}
复制代码

上述遍历写法,只有 forEach 在传入非箭头函数的时候会出现不一致的状况

建议使用箭头函数

Async/Await

async 异步编程中 forEach 则不会按照预期执行,以下:

// a undefined c
{(async () => {
    for (const iterator of array) {
        const result = await new Promise(res => setTimeout(() => { res(iterator) }, 1000))
        console.log(result)
    }
})()}

// a c
{(async () => {
    for (const key in array) {
        const result = await new Promise(res => setTimeout(() => { res(array[key]) }, 1000))
        console.log(result)
    }
})()}

// a undefined c
{(async () => {
    for (let index = 0; index < array.length; index++) {
        const result = await new Promise(res => setTimeout(() => { res(array[index]) }, 1000))
        console.log(result)
    }
})()}

// 语法错误
{(async () => {
    array.forEach(element => {
        const result = await new Promise(res => setTimeout(() => { res(element) }, 1000))
        console.log(result)
    })
})()}
复制代码

按照上述写法 forEach 会报错,首先看一下 forEach 的原理:

本质上 forEach 就像一个 for 循环的包装:

Array.prototype.forEach = function (callback) {
  for (let index = 0; index < this.length; index++) {
    callback(this[index], index, this)
  }
}
复制代码

若是按照上述写法,那么在回调函数内部调用 await 须要这个回调函数自己也是 async 函数,所以改成以下写法:

// 语法错误
{(async () => {
    array.forEach(async element => {
        const result = await new Promise(res => setTimeout(() => { res(element) }, 1000))
        console.log(result)
    })
})()}
复制代码

按照这样写法,forEach 最后会变成并行执行,而非串行。

所以建议使用 for-of 循环

或者建立一个 forEachAwait 方法:

async function forEachAwait(arr, cb) {
    for (let index = 0; index < array.length; index++) {
        await cb(arr[index], index, arr)
    }
}

// a undefined c
{(async () => {
    forEachAwait(array, async (elem) => {
        const result = await new Promise(res => setTimeout(() => { res(elem) }, 1000))
        console.log(result)
    })
})()}
复制代码

参考:

欢迎订阅个人公众号:

相关文章
相关标签/搜索