JavaScript循环到底是什么?

This article is a beginner's introduction to JavaScript loops. We'll go over why we need them, and how they fit into the front-end context. It’s a bird's eye view of accessing data and doing things to it, covering fundamental every-day concepts for a front-end developer.

本文是JavaScript循环的初学者介绍。 我们将讨论为什么需要它们,以及它们如何适应前端环境。 它是访问数据并对其进行处理的鸟瞰图,涵盖了前端开发人员的日常基本概念。

介绍。 (Introduction.)

“So we take this array, we iterate over it, we process the data and shazam!”When I first started learning to program, phrases like this sounded like mystical incantations. A language that looks like English but was beyond my comprehension. Coming from a non-engineering background I couldn’t for the life of me understand where a loop fit into what I was trying to do. And why exactly I needed it.

“因此,我们采用该数组,对其进行迭代,然后处理数据并进行shazam处理!” 当我第一次开始学习编程时,像这样的短语听起来像是神秘的咒语。 一种看起来像英语但无法理解的语言。 来自非工程领域的背景,我一生都无法理解循环在哪里适合我的工作。 以及为什么我确实需要它。

Nowadays, as a front-end developer, I use a loop for something or another all the time. But I haven't forgotten how mysterious it all was. My aim here is to give a high-level overview designed for people who have no engineering background. We will go beyond the syntax and instead focus on a real context of why we use loops and how it all fits together.

如今,作为前端开发人员,我一直都在使用循环进行某种或其他事情。 但是我没有忘记这一切多么神秘。 我的目的是为没有工程背景的人提供高层次的概述。 我们将超越语法,而将重点放在为什么使用循环以及循环如何组合的真实上下文上。

In this article, we will talk about how we access data and then how we do things to it with loops. More importantly, we are gonna try to answer why we need to do this. And how is this relevant to you building websites and web apps.

在本文中,我们将讨论如何访问数据,然后如何使用循环对数据进行处理。 更重要的是,我们将尝试回答为什么需要这样做。 以及这与您构建网站和Web应用程序有何关系

There’s also going to be a beginner-friendly practical example. You can follow along to it to practice the concepts and see them in action for yourself.

还将有一个适合初学者的实用示例。 您可以遵循它来实践这些概念,并亲自观察它们的实际效果。

设置 (The setup)

Let’s imagine that we are working on an online platform that allows us to do our supermarket shopping from a website. That's a real-world application of the things we want to talk about here.

假设我们正在一个在线平台上工作,该平台使我们可以从网站上进行超市购物。 这是我们要在此处讨论的事情的真实应用。

Take a look at Lola Market, which is where I work, for an example of how this would look like.

看看我工作的劳拉市场 ( Lola Market) ,举一个例子。

Assume we have a bunch of products stored in our database. Our task is to take these and display them on the website as a list. It’s a simple task that mimics things we do every day in the front end.

假设我们在数据库中存储了一堆产品。 我们的任务是获取这些并将它们作为列表显示在网站上。 这是一个简单的任务,它模仿了我们每天在前端所做的事情。

循环 (Loops)

To talk about loops we are going to be working with arrays. If you would like a refresher on what is an array and why we need it you can check out my article about it that links up nicely to this one.

谈论循环,我们将使用数组。 如果您想了解什么是数组以及为什么需要它,可以查看我有关它的文章,它很好地链接了该数组。

https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-array/

https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-array/

In short, we have taken a bunch of products that are in our database. We have packaged them in an array and made a request to bring them into our front-end code. And this is what this array looks like.

简而言之,我们已在数据库中获取了一堆产品。 我们将它们打包在一个数组中,并发出了将它们带入前端代码的请求。 这就是这个数组的样子。

Once we have the array of products that’s where the loops come in. Simply put, a loop is a way to take our array, “open” it and take one element out. Hand it to us to do what we want to it. Then repeat with the next element all the way to the end of the array.

一旦我们有了循环所需要的产品数组。简单来说,循环是一种获取数组,“打开”数组并取出一个元素的方法。 交给我们做我们想要做的事。 然后,从下一个元素一直重复到数组的结尾。

We use a loop when we need to repeat the same code for each one of the elements in our data.

当我们需要为数据中的每个元素重复相同的代码时,使用循环。

准备好 (Get set)

What we want to do is to display this list of products on the website. imagine it like this. Most websites would look more complex we hope. But this is just our first step.

我们要做的是在网站上显示此产品列表。 像这样想象。 我们希望大多数网站看起来会更复杂。 但这只是我们的第一步。

To keep the example simple and accessible to beginners we are going to use dev tools to do all the work. This requires no setup apart from opening your browser's dev tools.

为了使示例简单易懂,便于初学者使用,我们将使用开发工具来完成所有工作。 除了打开浏览器的开发工具外,无需任何设置。

We need to take a few things into account.

我们需要考虑一些事项。

  • We will not be making a call to the database to get our list of products. Instead, we will type an array by hand and use it directly in our front-end code.

    我们不会致电数据库来获取我们的产品列表。 相反,我们将手动键入一个数组,并直接在我们的前端代码中使用它。
  • We will not be displaying the list of products on a website. Instead we are only going to log the list into the dev tools console.

    我们不会在网站上显示产品列表。 相反,我们仅要将列表登录到开发工具控制台。
  • In the real world, we wouldn't be using the console.log() statements you see here. Instead  the logic we need to display our list on the website would be in its place.

    在现实世界中,我们不会使用您在此处看到的console.log()语句。 取而代之的是我们需要在网站上显示列表的逻辑。

OK, we are all set. Let's go.

好,我们都准备好了。 我们走吧。

对于每种产品 (For each product)

First, let’s take our loop and store it in a variable. This is to make it easier to read and work with.

首先,让我们开始循环,并将其存储在变量中 。 这是为了使其更易于阅读和使用。

const products = ['mushrooms', 'steak', 'fish', 'aubergines', 'lentils']

Now every time we use products we are actually referring to our array. This is very handy because our array could easily contain hundreds of products.

现在,每次使用products ,实际上是指阵列。 这非常方便,因为我们的阵列可以轻松包含数百种产品。

So, on we go to the main course, let me introduce you to the forEach()loop. And here is what it looks like in action:

因此,在进入主课程时,让我向您介绍forEach()循环。 这是实际的样子:

products.forEach( product => {
	// do stuff
 })

We will break this down piece by piece now. To begin with, let's convert this snippet of code into plain English. This literally reads: “Take the products array. For each element in this array, take that element, call it product and do stuff to it.”

我们现在将逐个细分。 首先,让我们将这段代码转换为简单的英语 。 字面意思为:“采用产品阵列。 对于这个阵列中的每个元素,采取的元素,把它product做的东西吧。”

Let’s take a closer look.

让我们仔细看看。

⬇ARRAY⬇  ⬇LOOP⬇  ⬇CURRENT⬇ ⬇FUNCTION⬇
products.forEach( product => {
	// do stuff
})
  • products: This is our array that contains the data.

    products :这是包含数据的数组

  • .forEach() : This is our array method, the loop.

    .forEach() :这是我们的数组方法,即loop

  • product : This is the currently selected element. This is the item from the array that our loop has picked up and given to us to work with.

    product :这是当前选择的元素。 这是我们的循环从数组中拾取并提供给我们使用的项目。

  • => { } : This is a function declaration, an arrow function to be specific. It roughly says “execute the following code.”

    => { } :这是一个函数声明,是一个特定的箭头函数。 它大致说“执行以下代码”。

  • // do stuff : This is where the actual code goes. Do things for each of the elements in the array.

    // do stuff :这是实际代码的去向。 对数组中的每个元素执行操作。

It is important to remember two things here about the currently selected element. First, that product is a variable name. The name itself is ours to decide, we could have called it food or x or anything else. However, if we are dealing with an array of products it is customary to use the singular for an individual item of that array: product. If it was an array of animals then we would call it animal.

重要的是要记住关于当前所选元素的两件事。 首先,该product是变量名。 名称本身是我们自己决定的,我们可以称它为foodx或其他名称。 但是,如果我们要处理的是products数组,则习惯将单数用于该数组的单个项目: product 。 如果是各种各样的animals那么我们称之为animal

Second, product changes with every round the loop does. Each time the loop picks an item  product becomes this new currently selected item.

其次, product在每个循环中都会变化。 每次循环选择一个商品时, product就会变成该新的当前所选商品。

Basically, the loop starts by picking up the first element in the array, “mushrooms” in this case. product now refers to “mushroom”. The loop then executes the function and runs the code that is there. Once it’s finished it goes back to the array and picks up the next element. product is no longer “mushrooms”, it is “steak” now. Once again the code executes. And this repeats for each one of the elements in the array.

基本上,循环从拾取数组中的第一个元素开始,在这种情况下为“蘑菇”。 product现在指的是“蘑菇”。 然后,循环执行该函数并运行其中的代码。 完成后,将返回数组并拾取下一个元素。 product不再是“蘑菇”,而是“牛排”。 再次执行代码。 并对数组中的每个元素重复此操作。

Each one of those rounds the loop makes is called an iteration.

循环进行的每一轮称为迭代

自己尝试 (Try it yourself)

So let’s try this out and see how it works. Go ahead and open the console in your browser’s dev tools. For example in Chrome it is Command + Option + J (Mac) or Control + Shift + J (Windows).

因此,让我们尝试一下,看看它是如何工作的。 继续并在浏览器的开发工具中打开控制台。 例如,在Chrome中,它是Command + Option + J(Mac)或Control + Shift + J(Windows)。

  • Type out our array saved in a variable const products = ['mushrooms', 'steak', 'fish', 'aubergines', 'lentils'].

    键入保存在变量const products = ['mushrooms', 'steak', 'fish', 'aubergines', 'lentils']的数组。

  • Hit enter. You’ll get an undefined. This is normal.

    按回车。 您会得到一个undefined 。 这是正常的。

  • Then type out our loop and this time we will add a  console.log() as the code to execute:

    然后键入我们的循环,这次我们将添加console.log()作为要执行的代码:

products.forEach( product => {
	console.log(product)
})

This is what it would look like:

看起来像这样:

What we want here is to print to the console the value that is product on each iteration. Try it for yourself. Hit enter.

我们这里想要的是将每次迭代的product值打印到控制台。 自己尝试一下。 按回车。

Once you do, the loop will start. For each product, it will log the currently selected one to the console until it’s done with all the products in our array.

完成后,循环将开始。 对于每种产品,它将当前选择的产品记录到控制台中,直到完成阵列中的所有产品为止。

And That's it. We have printed our entire array to the console. And we can use the same idea to manipulate the DOM to display and modify content on a website. Or do a myriad of other things with the data.

就是这样。 我们已将整个阵列打印到控制台。 而且,我们可以使用相同的想法来操纵DOM以显示和修改网站上的内容。 或对数据进行无数其他操作。

What about if we wanted to treat some of this data differently and not execute the same code for all the products? Say for example we want to show a "(v)" only next to vegetarian items.

如果我们想不同地对待其中一些数据并且不对所有产品执行相同的代码怎么办? 假设我们只想在素食旁边显示“(v)”。

In the following article, I explain just that. I take our example to the next step and talk about how conditionals allow us to do this - check it out!

在下面的文章中,我将对此进行解释。 我将把我们的例子带到下一步,并讨论条件式如何使我们做到这一点-看看吧!

https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-conditional-for/

https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-conditional-for/

结论 (Conclusion)

To recap, a loop takes our data (an array in this case) and allows us to access it. It then iterates over each element in the array and executes some code for each element.

回顾一下, 循环将获取我们的数据(在这种情况下为数组)并允许我们访问它。 然后,它遍历数组中的每个元素,并为每个元素执行一些代码。

I’m hoping that the next time you encounter a loop you will find it easier to understand how it works. And that it’s clearer why you might need one in a front-end context.

我希望下次遇到循环时,您会更容易理解它的工作原理。 而且很清楚为什么在前端环境中可能需要一个。

In this article, we saw a forEach() loop. But apart from the forEach(), there are many more loops and array methods to learn. From the most basic for loop to more advanced methods like map() and filter(). These are extremely powerful tools for development that you should get familiar with. You'll find yourself using them while working on any kind of application.

在本文中,我们看到了一个forEach()循环。 但是除了forEach() ,还有许多其他的循环数组方法需要学习。 从最基本的for循环到更高级的方法,例如map()filter() 。 这些是您应该熟悉的极其强大的开​​发工具。 在任何类型的应用程序上工作时,您都会发现自己在使用它们。

关闭 (Closure)

Thanks for reading. I hope you found this useful. And if you enjoyed it, sharing it around would be greatly appreciated. If you have any questions or comments I’m on Twitter @Syknapse and I would love to hear from you.

谢谢阅读。 希望您觉得这有用。 并且,如果您喜欢它,与周围分享它将不胜感激。 如果您有任何疑问或意见,我在Twitter @Syknapse上 ,我希望收到您的来信

My name is Syk and I’m a front-end developer at Lola Market in Madrid. I career-changed into web dev from an unrelated field, so I try to create content for those on a similar journey. My DMs are always open for aspiring web developers in need of some support. You can also read about my transformation in this article.

我叫Syk,是马德里Lola Market的前端开发人员。 我从一个无关领域转变为Web开发人员,因此我尝试为类似旅程中的人员创建内容。 我的DM总是向有需要的Web开发人员开放。 您还可以在本文中了解我的转型

https://www.freecodecamp.org/news/how-i-switched-careers-and-got-a-developer-job-in-10-months-a-true-story-b8895e855a8b/

https://www.freecodecamp.org/news/how-i-switched-careers-and-got-a-developer-job-in-10-months-a-true-story-b8895e855a8b/



翻译自: https://www.freecodecamp.org/news/what-in-the-world-is-a-javascript-loop-for/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值