This article will provide you with a solid understanding of exactly how to iterate over an Array data structure in JavaScript.

本文将为您提供对如何迭代JavaScript中的Array数据结构的扎实理解。

Whether you are just beginning to learn JavaScript or are here for a refresher, there will be value for you either way. This article will walk you through one of the most widely used JavaScript concepts.

无论您是刚刚开始学习JavaScript还是在这里进行复习,无论哪种方式都将为您带来价值。 本文将引导您完成使用最广泛JavaScript概念之一。

什么是数组? (What is an array?)

let cars = ["Tesla", "Ferrari", "Lamborghini", "Audi"];

Above is a JavaScript array used to store multiple values. This is one of the simplest forms of an array. It contains 4 “elements” inside the array, all strings. And as you can see each element is separated by a comma.

上面是一个用于存储多个值JavaScript数组。 这是数组的最简单形式之一。 它在数组内部包含4个“元素”,所有字符串。 如您所见,每个元素都用逗号分隔。

This example array holds different makes of cars, and can be referred to with the cars variable.

此示例数组包含不同品牌的汽车,并且可以使用cars变量来引用。

There are a number of ways we can iterate over this array. JavaScript is incredibly feature-rich, so we have the luxury to choose the best way to solve our problem.

我们可以通过多种方法来迭代此数组。 JavaScript具有令人难以置信的丰富功能,因此我们可以选择最佳的方法来解决问题。

Here’s how we will tackle iterating over arrays in JavaScript:

这是解决JavaScript中数组迭代的方法:

  1. Highlight 5 common methods to iterate over an array重点介绍5种遍历数组的常用方法
  2. Show some insights into each iterative method对每种迭代方法显示一些见解
  3. Provide some code you can use to test it out, too!提供一些代码,您也可以使用它进行测试!

传统For循环 (Traditional For Loop)

什么是For循环? (What is a For Loop? )

Wikipedia defines a For Loop as:

维基百科将For循环定义为:

“In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly.”

“在计算机科学中 , for循环 (或简称为for循环 )是用于指定迭代的控制流 语句 , 语句 允许 重复 执行 代码 。”

A for loop is a way to execute code repeatedly. Instead of typing out console.log(“hi”) five times, you could wrap it inside a for loop.In this first example, we will learn how to iterate over the cars array you have seen above, and print out every element. The iterator, or counter, will start at the first index “Tesla” and finish at the last “Audi”. It moves through the array and prints one element at a time.

for循环是一种重复执行代码的方法。 您可以将其包装在for循环中,而不必重复输入console.log(“hi”)五次。在第一个示例中,我们将学习如何遍历上面看到的cars数组,并打印出每个元素。 迭代器或计数器将在第一个索引“ Tesla”处开始,并在最后一个“ Audi”处结束。 它遍历数组并一次打印一个元素。

let cars = ["Tesla", "Ferrari", "Lamborghini", "Audi"];for(let i = 0; i < cars.length; i++) {console.log(cars[i]);
}

Output:

输出:

Tesla
Ferrari
Lamborghini
Audi

Diving into the code, we pass three options to the for loop

深入研究代码,我们将三个选项传递给for循环

  • the iterator variable - let i = 0;

    迭代器变量- let i = 0;

  • where the iterator should stop - i < card.length

    迭代器应停止的位置i < card.length

  • how much to increment the iterator each loop - i++

    每个循环增加多少迭代器i++

This loop starts us at 0, increases the variable by one each loop, and stops when we hit the last element in the array.

此循环从0开始,使变量每个循环增加一个,并在我们击中数组中的最后一个元素时停止。

The key benefit of the traditional for loop is that you have more control. It’s possible to access different elements within the array, or iterate through the array in a sophisticated way to solve a complex problem. For example, skipping every other element in the array can be done quite easily with the traditional for loop.

传统for循环的主要好处是您拥有更多控制权。 可以访问数组中的不同元素,或者以复杂的方式遍历数组以解决复杂的问题。 例如,使用传统的for循环可以很容易地跳过数组中的所有其他元素。

forEach方法 (The forEach method)

什么是forEach方法? (What is the forEach method? )

The forEach method is used to execute a function for each element of your array. This method is a great choice if the length of the array is “unknown”, or guaranteed to change. This method can be only used with Arrays, Sets, and Maps.

forEach方法用于为数组的每个元素执行一个函数。 如果数组的长度是“未知”或保证会改变,则此方法是一个不错的选择。 此方法只能与数组,集合和映射一起使用。

const amounts = [65, 44, 12, 4];
let doubledAmounts = [];amounts.forEach(item => {doubledAmounts.push(item * 2);
})console.log(doubledAmounts);

The greatest benefit of a forEach loop is being able to access each item, even if your array is likely to grow in size. It is a scalable solution for many use-cases and is easier to read and understand than a traditional for loop because we know we will iterate over each element exactly once.

forEach循环的最大好处是即使数组的大小可能会增加,也能够访问每个项目。 它是适用于许多用例的可伸缩解决方案,比传统的for循环更易于阅读和理解,因为我们知道我们将对每个元素进行精确的迭代一次。

While循环 (While loop)

什么是While循环? (What is a While Loop? )

Wikipedia defines a While Loop as:

维基百科将While循环定义为:

“A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

while循环是一个控制流 语句 ,它允许基于给定的布尔条件重复执行代码。 while循环可被视为重复的if语句 。

A while loop is a way to execute code repeatedly to check if a condition is true or false. So, instead of using a for loop, with a nested if statement, we can use a while loop. Or, if we're not able to find the length of the array, while loops are an excellent choice.

while循环是一种重复执行代码以检查条件是对还是假的方法。 因此,我们可以使用while循环,而不是使用带有嵌套if语句的for循环。 或者,如果我们无法找到数组的长度,则while循环是一个不错的选择。

The while loop is often controlled by a counter. In the example below we show a basic while loop iterating through an array. The key is to have control over the while loop you are creating.

while循环通常由计数器控制。 在下面的示例中,我们显示了遍历数组的基本while循环。 关键是要控制正在创建的while循环。

While Loop Example (Good):

While循环示例(良好):

let i = 0 while (i < 5) { console.log(i); i++;
}

Output:

输出

0
1
2
3
4

The while loop's if statement is i < 5, or spoken aloud, "i is less than 5". The variable i is incremented every time the loop runs.

while循环的if语句为i < 5或大声说“ i小于5”。 每次循环运行时,变量i都会增加。

In simple terms, this means that 1 is added to the variable i every time the loop performs a full iteration. On the first iteration, i is equal to 0, and we print “0” to the console.

简单来说,这意味着每次循环执行完整迭代时,都会将1加到变量i 。 在第一次迭代中, i等于0,我们在控制台上打印“ 0”。

The greatest risk of using a while loop is writing a condition which is never met.

使用while循环的最大风险是编写从未满足的条件。

This occurs frequently in real-world scenarios, where someone writes a while loop but forgets to test their loop, and it introduces an infinite loop into the code-base.

在现实世界中,这种情况经常发生,有人编写了while循环,但忘记测试他们的循环,并且在代码库中引入了无限循环 。

An infinite loop occurs when the condition is never met, and the loop keeps running forever. This often results in breaking changes, which then causes the entire software application to break and stop working.

当永不满足条件时,将发生无限循环,并且该循环将永远运行。 这通常会导致更改中断,然后导致整个软件应用程序中断并停止工作。

Warning: Do not run this code. Infinite Loop Example (Bad):

警告:请勿运行此代码。 无限循环示例(错误):

let i = 0 while (i < 5) { console.log(i);
}

Output: Results may vary.

输出:结果可能会有所不同。

Do While循环 (The Do While Loop)

什么是while循环? (What is a do while loop? )

Wikipedia defines a Do-While loop as:

Wikipedia将Do-While循环定义为:

“a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.”

do while循环是一个控制流 语句 ,它至少执行一次代码块,然后根据代码块末尾的给定布尔条件,是否重复执行该代码块。”

A do-while loop is almost identical to a while loop, however there is one key difference. The do-while loop will guarantee to always execute the block of code at least once before the if statement is checked.

do-while循环与while循环几乎相同,但是有一个关键的区别。 do-while循环将确保在检查if语句之前始终至少执行一次代码块。

I often think of it as a reverse while loop, and almost never use them. However, they do come in handy in some very specific scenarios.

我经常将其视为反向while循环,并且几乎从不使用它们。 但是,它们确实在某些非常特定的场景中派上了用场。

Do-Loop Example (Good):

循环示例(良好):

let i = 0; do { console.log(i); i++;
} while (i < 5);

Output:

输出

0
1
2
3
4

The greatest risk of using a do-loop is writing a condition which is never met. (Same as with a While Loop.)

使用do循环的最大风险是编写从未满足的条件。 (与While循环相同。)

Warning: Do not run this code. Infinite Loop Example (Bad):

警告:请勿运行此代码。 无限循环示例(错误):

let i = 0; do { console.log(i);
} while (i < 5);

Output: Results may vary.

输出 :结果可能会有所不同。

Want to take your JavaScript knowledge to the next level? Learn about map, which is the same as forEach, but with a bonus!!

JS For循环教程–如何在JavaScript中遍历数组相关推荐

  1. 遍历 in java_[Java教程]JavaScript中遍历数组 最好不要使用 for in 遍历

    [Java教程]JavaScript中遍历数组 最好不要使用 for in 遍历 0 2017-01-14 00:01:52 先看一段代码1 2 3 4 5 Document 6 7 8 9 21 2 ...

  2. 如何在JavaScript中比较数组?

    本文翻译自:How to compare arrays in JavaScript? I'd like to compare two arrays... ideally, efficiently. 我 ...

  3. JavaScript中遍历数组的方法

    目录 JavaScript中遍历数组的方法 1.for 循环遍历 2.forEach 遍历 3.map 遍历 4.for...of 遍历 5.filter 遍历 6.some 遍历 7.keys,va ...

  4. JavaScript中遍历数组小问题

    JavaScript中遍历数组小问题 1. break.return对遍历的影响 const arr = [1, 2, 3, 4, 5, 6]; for - break for (let i = 0; ...

  5. JavaScript中遍历数组的for for-in和forEach三种方式

    JavaScript中遍历数组的for for-in和forEach三种方式 for循环 let arr = [1,2,3,4,5,6];for(let i = 0; i < arr.lengt ...

  6. javascript字典中添加数组_如何在JavaScript中使用数组方法:Mutator方法

    JavaScript中的数组由元素列表组成.JavaScript有许多有用的内置方法来处理数组.修改原始数组的方法称为mutator方法,返回新值或表示的方法称为accessor方法.在本教程中,我们 ...

  7. 如何在 JavaScript 中清空数组?

    问: 这个问题的答案是社区的努力.编辑现有答案以改进这篇文章.它目前不接受新的答案或交互. 有没有办法清空数组,如果可能的话,可以使用 .remove()? 例如, A = [1,2,3,4]; 我怎 ...

  8. html页面取js里面的值,如何在javascript中获取HTML元素的样式值?

    这个element.style属性只让您知道定义为内联在该元素(以编程方式或在元素的样式属性中定义)中,您应该获得计算样式. 用跨浏览器的方式做它并不容易,IE有自己的方式,通过element.cur ...

  9. 如何在JavaScript中克隆数组

    JavaScript has many ways to do anything. I've written on 10 Ways to Write pipe/compose in JavaScript ...

最新文章

  1. 广东蓝桥杯c语言编译器_小软访谈之榜样充电站 千里之行,始于足下——“蓝桥杯”获奖者采访...
  2. 怎样知道邮箱的端口_网络端口介绍
  3. Tomcat意外宕机分析
  4. python爬虫框架排行榜-常用python爬虫框架整理
  5. Quartz.net基于数据库的任务调度管理(Only.Jobs)
  6. Asp.net core与golang web简单对比测试
  7. java中存在对多个对象加锁的情况_Java对象锁和类锁全面解析(多线程synchronized关键字)...
  8. 基础才是重中之重~通过人类的生活来学习Delegate
  9. WARNING: IPv4 forwarding is disabled. Networking will not work.
  10. ITIL 4Foundation认证
  11. EMLOG模板 自适应Fontopen3 可做企业站
  12. 《甄嬛传》影评(整理)
  13. IPA转APP的方法和APP转IPA的方法
  14. android os 1.5 下载地址,技德Remix OS 1.5发布 适配Android 5.0
  15. 【Java并发】同步模式之保护性暂停
  16. 怎样看待中小学stem教育特点
  17. 标签如何显示药品生僻字、特殊图标?上海瀚示灯光拣选系统在智能药房的应用...
  18. Ubuntu QQ2009
  19. java tif切割成瓦片_将图片切割成瓦片图-(算法+实现)
  20. 基恩士 梯形图转化为c语言,基恩士PLC梯形图和脚本的融合技巧.pdf

热门文章

  1. 超简单,Python爬取阴阳师原画壁纸
  2. R语言函数式编程(Functional Programming)概念
  3. PHPCMS学习手记(一)-----------初识模板
  4. UE4 Actor生命周期 SpawnActor DestroyActor剖析
  5. CSS 3之模糊与透明色背景
  6. python_飞机大战_boss_py_六
  7. 小偷模拟器 Thief Simulator V20230207 最新中文学习版 单机游戏游戏下载免安装【3.27G】
  8. ajax跨域的几种解决方案
  9. window桌面版太空人
  10. android 自动对焦pk,Android拍照机皇大PK i9100对决LT18i