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

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!! 🎉

是否想将您JavaScript知识提升到一个新的水平? 了解map ,它与forEach相同,但有奖励!! 🎉

奖励示例(地图迭代) (BONUS Example (Iteration with map))

什么是地图? (What is map? )

Wikipedia defines a map as:

维基百科将地图定义为:

“In many programming languages, map is the name of a higher-order function that applies a given function to each element of a functor, e.g. a list, returning a list of results in the same order. It is often called apply-to-all when considered in functional form.”

“在许多编程语言中map将给定功能应用于函子的每个元素的高阶函数的名称,例如list ,以相同顺序返回结果列表。 以功能形式考虑时,它通常被称为“ 适用于所有人 ”。

How does it work? The map function in JavaScript applies a function to every element inside the array. Please take a moment to re-read that sentence.

它是如何工作的? JavaScript中的map函数将函数应用于数组内的每个元素 请花一点时间重新阅读该句子。

Afterwards, the map function returns a new array with the results of applying a function to every element in the array.

之后, map函数将返回一个新数组,并将该函数应用于该数组中的每个元素。

Map example:

地图示例:

const array = [1, 1, 1, 1];

// pass a function to map
const results = array.map(x => x * 2);

console.log(results);

Output:

输出

[2,2,2,2]

We have applied the map function to the array containing four 1's. The map function then multiplied each element by 2, i.e., x * 2, and returned a new array. The new array was then stored in the results variable.

我们已将map函数应用于包含四个1的数组。 然后, map函数将每个元素乘以2,即x * 2 ,并返回一个新数组。 然后将新数组存储在results变量中。

By viewing our output, we can see this worked successfully. Every element in the array has been multiplied by 2. This method can be used as a replacement to a loop in some cases, and is incredibly powerful.

通过查看我们的输出,我们可以看到此方法成功完成。 数组中的每个元素都已乘以2。在某些情况下,该方法可以用作循环的替代方法,并且功能非常强大。

结论 (Conclusion )

Well done! You have learned five different ways to iterate over an array in JavaScript. These are the fundamental building blocks that will set you up for success in your JavaScript programming journey.

做得好! 您已经学习了五种不同的方法来遍历JavaScript中的数组。 这些是基本的构建块,可帮助您成功完成JavaScript编程之旅。

You have also been exposed to an advanced concept, map, which is used often in large-scale software applications.

您还将接触到高级概念map ,该概念经常在大型软件应用程序中使用。

So, I’ll leave you with this: how are you going to use arrays in your projects? And which iteration method did you find most exciting?  

因此,我将为您提供这一点:您将如何在项目中使用数组? 您觉得哪种迭代方法最令人兴奋?

Thanks for reading!

谢谢阅读!

If you liked my article, please follow me and/or send me a message!  

如果您喜欢我的文章,请关注我和/或给我发送消息!

TwitterMediumGithub

TwitterGithub

翻译自: https://www.freecodecamp.org/news/javascript-loop-tutorial-how-to-iterate-over-an-array-in-javascript/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值