我们有多种方法来遍历 JavaScript 的数组或者对象,而它们之间的区别非常让人疑惑。Airbnb 编码风格禁止使用 for/in 与 for/of,你知道为什么吗?

这篇文章将详细介绍以下 4 种循环语法的区别:

  • for (let i = 0; i < arr.length; ++i)
  • arr.forEach((v, i) => { /* ... */ })
  • for (let i in arr)
  • for (const v of arr)

语法

使用for和for/in,我们可以访问数组的下标,而不是实际的数组元素值:

for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
} for (let i in arr) {
console.log(arr[i]);
}

使用for/of,则可以直接访问数组的元素值:

for (const v of arr) {
console.log(v);
}

使用forEach(),则可以同时访问数组的下标与元素值:

arr.forEach((v, i) => console.log(v));

非数字属性

JavaScript 的数组就是 Object,这就意味着我们可以给数组添加字符串属性:

const arr = ["a", "b", "c"];

typeof arr; // 'object'

arr.test = "bad"; // 添加非数字属性

arr.test; // 'abc'
arr[1] === arr["1"]; // true, JavaScript数组只是特殊的Object

4 种循环语法,只有for/in不会忽略非数字属性:

const arr = ["a", "b", "c"];
arr.test = "bad"; for (let i in arr) {
console.log(arr[i]); // 打印"a, b, c, bad"
}

正因为如此,使用for/in遍历数组并不好。

其他 3 种循环语法,都会忽略非数字属性:

const arr = ["a", "b", "c"];
arr.test = "abc"; // 打印 "a, b, c"
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
} // 打印 "a, b, c"
arr.forEach((el, i) => console.log(i, el)); // 打印 "a, b, c"
for (const el of arr) {
console.log(el);
}

要点: 避免使用for/in来遍历数组,除非你真的要想要遍历非数字属性。可以使用 ESLint 的guard-for-in规则来禁止使用for/in。

数组的空元素

JavaScript 数组可以有空元素。以下代码语法是正确的,且数组长度为 3:

const arr = ["a", , "c"];

arr.length; // 3

让人更加不解的一点是,循环语句处理['a',, 'c']与['a', undefined, 'c']的方式并不相同。

对于['a',, 'c'],for/in与forEach会跳过空元素,而for与for/of则不会跳过。

// 打印"a, undefined, c"
for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
} // 打印"a, c"
arr.forEach(v => console.log(v)); // 打印"a, c"
for (let i in arr) {
console.log(arr[i]);
} // 打印"a, undefined, c"
for (const v of arr) {
console.log(v);
}

对于['a', undefined, 'c'],4 种循环语法一致,打印的都是"a, undefined, c"。

还有一种添加空元素的方式:

// 等价于`['a', 'b', 'c',, 'e']`
const arr = ["a", "b", "c"];
arr[5] = "e";

还有一点,JSON 也不支持空元素:

JSON.parse('{"arr":["a","b","c"]}');
// { arr: [ 'a', 'b', 'c' ] } JSON.parse('{"arr":["a",null,"c"]}');
// { arr: [ 'a', null, 'c' ] } JSON.parse('{"arr":["a",,"c"]}');
// SyntaxError: Unexpected token , in JSON at position 12

要点: for/in与forEach会跳过空元素,数组中的空元素被称为"holes"。如果你想避免这个问题,可以考虑禁用forEach:

parserOptions:
ecmaVersion: 2018
rules:
no-restricted-syntax:
- error
- selector: CallExpression[callee.property.name="forEach"]
message: Do not use `forEach()`, use `for/of` instead

函数的 this

for,for/in与for/of会保留外部作用域的this。

对于forEach, 除非使用箭头函数,它的回调函数的 this 将会变化。

使用 Node v11.8.0 测试下面的代码,结果如下:

"use strict";

const arr = ["a"];

arr.forEach(function() {
console.log(this); // 打印undefined
}); arr.forEach(() => {
console.log(this); // 打印{}
});

要点: 使用 ESLint 的no-arrow-callback规则要求所有回调函数必须使用箭头函数。

Async/Await 与 Generators

还有一点,forEach()不能与 Async/Await 及 Generators 很好的"合作"。

不能在forEach回调函数中使用 await:

async function run() {
const arr = ['a', 'b', 'c'];
arr.forEach(el => {
// SyntaxError
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(el);
});
}

不能在forEach回调函数中使用 yield:

function run() {
const arr = ['a', 'b', 'c'];
arr.forEach(el => {
// SyntaxError
yield new Promise(resolve => setTimeout(resolve, 1000));
console.log(el);
});
}

对于for/of来说,则没有这个问题:

async function asyncFn() {
const arr = ["a", "b", "c"];
for (const el of arr) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log(el);
}
} function* generatorFn() {
const arr = ["a", "b", "c"];
for (const el of arr) {
yield new Promise(resolve => setTimeout(resolve, 1000));
console.log(el);
}
}

当然,你如果将forEach()的回调函数定义为 async 函数就不会报错了,但是,如果你想让forEach按照顺序执行,则会比较头疼。

下面的代码会按照从大到小打印 0-9:

async function print(n) {
// 打印0之前等待1秒,打印1之前等待0.9秒
await new Promise(resolve => setTimeout(() => resolve(), 1000 - n * 100));
console.log(n);
} async function test() {
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(print);
} test();

要点: 尽量不要在forEach中使用 aysnc/await 以及 generators。

结论

简单地说,for/of是遍历数组最可靠的方式,它比for循环简洁,并且没有for/in和forEach()那么多奇怪的特例。for/of的缺点是我们取索引值不方便,而且不能这样链式调用forEach(). forEach()。

使用for/of获取数组索引,可以这样写:

for (const [i, v] of arr.entries()) {
console.log(i, v);
}

参考

关于Fundebug

Fundebug专注于JS、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java线上应用实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了10亿+错误事件,付费客户有Google、360、金山软件、百姓网等众多品牌企业。欢迎大家免费试用!

版权声明

转载时请注明作者Fundebug以及本文地址:

https://blog.fundebug.com/2019/03/11/4-ways-to-loop-array-inj-javascript/

JavaScript 的 4 种数组遍历方法: for VS forEach() VS for/in VS for/of的更多相关文章

  1. js几种数组遍历方法.

    第一种:普通的for循环 ; i < arr.length; i++) { } 这是最简单的一种遍历方法,也是使用的最多的一种,但是还能优化. 第二种:优化版for循环 ,len=arr.len ...

  2. JavaScript里面9种数组遍历!

    ​大家好,我在这里总结分享了JavaScript中的闹腾的数组循环家族. 1.大家最常用的for循环,我就不解释了: for(let i = 0; i < 5 ; i++){ console.l ...

  3. JavaScript 数组 遍历方法 map( ) 和 forEach( )

    let arr = [1, 3, 7, 6, 9]; 不用知道元素的个数,即不用设置开始下标和结束下标. 1:forEach( )会把数组中的每个值进行操作,没有返回值,undefined let j ...

  4. JavaScript 中的12种循环遍历方法

    原文:JavaScript 中的12种循环遍历方法 题目:请介绍 JavaScript 中有哪些循环和遍历的方法,说说它们的应用场景和优缺点? 1.for 循环 let arr = [1,2,3];f ...

  5. 浅谈6种JS数组遍历方法的区别

    本篇文章给大家介绍一下6种JS数组遍历方法:for.foreach.for in.for of.. each. ().each的区别.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. ...

  6. ES6 数组遍历方法的实战用法总结(forEach,every,some,map,filter,reduce,reduceRight,indexOf,lastIndexOf)

    目录 forEach every some map filter reduce && reduceRight indexOf lastIndexOf 前言 ES6原生语法中提供了非常多 ...

  7. js数组遍历方法总结

    数组遍历方法 1.for循环 使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组较大时优化效果才会比较明显. 1 2 3 for(j = 0,len=arr.length; j < le ...

  8. JS数组遍历方法

    常用数组遍历方法: 1.原始for循环 var a = [1,2,3]; for(var i=0;i<a.length;i++){ console.log(a[i]); //结果依次为1,2,3 ...

  9. 数组遍历方法forEach 和 map 的区别

    数组遍历方法forEach 和 map 的区别:https://www.cnblogs.com/sticktong/p/7602783.html

随机推荐

  1. 最基础的Eureka服务和注册搭建

    Eureka服务端 打开IDEA,新建项目 选择"next",写上组织名(Group)和项目名(Artifact) 选择如下选项,然后一直下一步,创建好项目. 删除不必要的文件 添 ...

  2. UEditor之实现配置简单的图片上传示例

    UEditor之实现配置简单的图片上传示例 原创 2016年06月11日 18:27:31 开心一笑 下班后,阿华到楼下小超市买毛巾,刚买完出来,就遇到同一办公楼里另一家公司的阿菲,之前与她远远的有过 ...

  3. 多选ui实现单选效果

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. emWin智能家居主界面设计,含uCOS-III和FreeRTOS两个版本

    第6期:智能家居主界面设计配套例子:V6-910_STemWin提高篇实验_智能家居主界面设计(uCOS-III)V6-911_STemWin提高篇实验_智能家居主界面设计(FreeRTOS) 例程下 ...

  5. Http 1.x弊端与Http 2.0比较

    HTTP2.0作为新版协议,改动细节必然很多,不过对应用开发者和服务提供商来说,影响较大的就几点. 新的二进制格式(Binary Format) http1.x诞生的时候是明文协议,其格式由三部分组成 ...

  6. [Swift]LeetCode337. 打家劫舍 III | House Robber III

    The thief has found himself a new place for his thievery again. There is only one entrance to this a ...

  7. Mysql、Hbuilder、Idea快捷键

    MyEclipse 快捷键 ↑ ↓ ← →多 1.方法抽取,Alt+Shift+M 2.多行注释:Ctrl+Shift+/ 3.对象.方法; Ctrl+2 + ↓+回车 ,自动生成返回类型和变量 (非 ...

  8. 有点深度的聊聊JDK动态代理

    在接触SpringAOP的时候,大家一定会被这神奇的功能所折服,想知道其中的奥秘,底层到底是如何实现的.于是,大家会通过搜索引擎,知道了一个陌生的名词:动态代理,慢慢的又知道了动态代理有多种实现方式, ...

  9. Python内置函数(67)——zip

    英文文档: zip(*iterables) Make an iterator that aggregates elements from each of the iterables. Returns ...

  10. FTP解决连接慢问题

    今天发现程序报登录FTP超时,于是便手动登录发现真的慢,于是网上搜便获取大招亲测有效,于是怕忘的我马上记录下来,zzzzzzz!! 如下解决 vim /etc/vsftpd/vsftpd.conf 在 ...