search
HomeWeb Front-endJS TutorialThe difference between the four array traversal methods in JS ( for , forEach() , for/in, for/of)

The difference between the four array traversal methods in JS ( for , forEach() , for/in, for/of)

We have multiple ways to traverse JavaScript arrays or objects, and the differences between them are very confusing. Airbnb Coding StyleFor/in and for/of are prohibited, do you know why? This article will introduce in detail the differences between the following four loop syntaxes:

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

Use

for

and for/in, we can access the subscript of the array instead of the actual array element value: <pre class='brush:php;toolbar:false;'>for (let i = 0; i &lt; arr.length; ++i) { console.log(arr[i]); } for (let i in arr) { console.log(arr[i]); }</pre>Using

for/of

, we can directly access the element value of the array : <pre class='brush:php;toolbar:false;'>for (const v of arr) { console.log(v); }</pre>Using

forEach()

, you can access the subscript and element value of the array at the same time: <pre class='brush:php;toolbar:false;'>arr.forEach((v, i) =&gt; console.log(v));</pre>Non-numeric attributes

JavaScript array It is Object, which means that we can add string attributes to the array:

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

typeof arr; // &#39;object&#39;

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

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

4 loop syntaxes, only

for/in

will not ignore non-numeric attributes: <pre class='brush:php;toolbar:false;'>const arr = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]; arr.test = &quot;bad&quot;; for (let i in arr) { console.log(arr[i]); // 打印&quot;a, b, c, bad&quot; }</pre> Because of this,

it is not good to

use for/in to traverse an array. The other three loop syntaxes will ignore non-numeric attributes:

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);
}

Points:

Avoid using for/in to traverse the array unless you Really want to iterate over non-numeric properties. You can use ESLint's guard-for-in rule to disable the use of for/in. Empty elements of arrays

JavaScript arrays can have

empty elements

. The following code syntax is correct, and the array length is 3:

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

arr.length; // 3
What makes people even more confused is that the loop statement handles

['a',, 'c']

and ['a', undefined, 'c'] is not the same. For

['a',, 'c']

, for/in and forEach will skip empty elements, while for and for/of will not be skipped. <pre class='brush:php;toolbar:false;'>// 打印&quot;a, undefined, c&quot; for (let i = 0; i &lt; arr.length; ++i) { console.log(arr[i]); } // 打印&quot;a, c&quot; arr.forEach(v =&gt; console.log(v)); // 打印&quot;a, c&quot; for (let i in arr) { console.log(arr[i]); } // 打印&quot;a, undefined, c&quot; for (const v of arr) { console.log(v); }</pre>For

['a', undefined, 'c']

, the four loop syntaxes are the same, and "a, undefined, c" ​​is printed. There is another way to add empty elements:

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

One more thing, JSON does not support empty elements either:

JSON.parse(&#39;{"arr":["a","b","c"]}&#39;);
// { arr: [ &#39;a&#39;, &#39;b&#39;, &#39;c&#39; ] }

JSON.parse(&#39;{"arr":["a",null,"c"]}&#39;);
// { arr: [ &#39;a&#39;, null, &#39;c&#39; ] }

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

Points:

for/in and forEach will skip empty elements. Empty elements in the array are called "holes". If you want to avoid this problem, consider disabling the forEach:<pre class='brush:php;toolbar:false;'>parserOptions: ecmaVersion: 2018 rules: no-restricted-syntax: - error - selector: CallExpression[callee.property.name=&quot;forEach&quot;] message: Do not use `forEach()`, use `for/of` instead</pre> function of this

for

, for/in and for/of will retain this of the outer scope. For

forEach

, unless an arrow function is used, the this of its callback function will change. Use Node v11.8.0 to test the following code, the results are as follows:

"use strict";

const arr = ["a"];

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

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

Points:

Use ESLint's no-arrow-callbackThe rules require that all callback functions must use arrow functions. Async/Await and Generators

One more thing,

forEach()

cannot "cooperate" well with Async/Await and Generators. Cannot use await in the

forEach

callback function: <pre class='brush:php;toolbar:false;'>async function run() { const arr = [&amp;#39;a&amp;#39;, &amp;#39;b&amp;#39;, &amp;#39;c&amp;#39;]; arr.forEach(el =&gt; { // SyntaxError await new Promise(resolve =&gt; setTimeout(resolve, 1000)); console.log(el); }); }</pre>Cannot use yield in the

forEach

callback function: <pre class='brush:php;toolbar:false;'>function run() { const arr = [&amp;#39;a&amp;#39;, &amp;#39;b&amp;#39;, &amp;#39;c&amp;#39;]; arr.forEach(el =&gt; { // SyntaxError yield new Promise(resolve =&gt; setTimeout(resolve, 1000)); console.log(el); }); }</pre> For

for/of

, there is no such problem: <pre class='brush:php;toolbar:false;'>async function asyncFn() { const arr = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]; for (const el of arr) { await new Promise(resolve =&gt; setTimeout(resolve, 1000)); console.log(el); } } function* generatorFn() { const arr = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]; for (const el of arr) { yield new Promise(resolve =&gt; setTimeout(resolve, 1000)); console.log(el); } }</pre> Of course, if you define the callback function of

forEach()

as an async function, no error will be reported However, if you want forEach to be executed in order, it will be a headache. The following code will print 0-9 from large to small:

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();

Points:

Try not to use aysnc/await in forEach and generators. Conclusion

Simply put,

for/of

is the most reliable way to traverse an array. It is more concise than the for loop and has no for/in and forEach()So many strange special cases. The disadvantage of for/of is that it is inconvenient for us to get the index value, and we cannot call forEach(). forEach() in a chain like this. <p>使用<code>for/of获取数组索引,可以这样写:

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

参考

本文采用意译,版权归原作者所有

原文:http://thecodebarbarian.com/for-vs-for-each-vs-for-in-vs-for-of-in-javascript.html

相关免费学习推荐:js视频教程

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of The difference between the four array traversal methods in JS ( for , forEach() , for/in, for/of). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:fundebug. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor