by Zell Liew

由Zell Liew

JavaScript Essentials:如何为循环而烦恼 (JavaScript Essentials: how to wrap your head around for loops)

Let’s say you want to run a function, bounceBall, four times. How would you do it? Like this?

假设您要运行一次功能bounceBall四次。 你会怎么做? 像这样?

function bounceBall() {   // bounce the ball here }
bounceBall() bounceBall() bounceBall() bounceBall()

This approach is great if you need to bounceBall only for a few times. What happens if you need to bounceBall for a hundred times?

如果只需要bounceBall则此方法非常bounceBall 。 如果您需要bounceBall一百次球怎么办?

The better way is through a for loop.

更好的方法是通过for循环。

“ for”循环 (The ‘for’ loop)

The for loop runs a block of code as many times as you want to. Here’s a for loop that runs bounceBall ten times:

for循环可以运行一块代码多次。 这是一个运行bounceBall十次的for循环:

for (let i = 0; i < 10; i++) {   bounceBall() }

It’s broken down into four parts — the initialExpression, the condition, the incrementalExpression , and the statement:

它分为四个部分initialExpressionconditionincrementalExpressionstatement

for (initialExpression; condition; incrementExpression) {   statement }

Before you loop, you need to have a statement. This statement is the block of code you’d like to run multiple times. You can write any number of lines of code here. You can even use functions.

在循环之前,您需要有一条声明 。 该语句是您希望多次运行的代码块。 您可以在此处编写任意多行代码。 您甚至可以使用功能。

Here’s what the for loop looks like with bounceBall as its statement:

这是使用bounceBall作为语句的for循环的样子:

for (initialExpression; condition; incrementExpression) {     bounceBall() }

Next, you need an initial expression to begin a loop. This is where you declare a variable. For most loops, this variable is called i. It’s also set to 0.

接下来,您需要一个初始表达式来开始循环。 在这里声明变量。 对于大多数循环,此变量称为i 。 也设置为0。

Here’s how it’ll look like when you put the initialExpression into the for loop:

当您将initialExpression放入for循环时,它的外观如下:

for (let i = 0; condition; incrementExpression) {   bounceBall() }

After the statement runs, the variable, i is increased or decreased. You increase or decrease the value of i in the increment expression.

语句运行后,变量i增大或减小。 您可以在增量表达式中增加或减少i的值。

To increase the value of i by one, you reassign i such that it becomes i + 1 with i = i + 1. The shorthand for this reassignment is i++, which is what you’ll find in most for loops.

若要将i的值增加1,请重新分配i ,使其在i = i + 1时变为i + 1 。 这种重新分配的简写是i++ ,这是您在大多数for循环中都可以找到的。

To decrease the value of i by one, you reassign i such that it becomes i - 1 with i = i - 1. The shorthand for this reassignment is i--, which is another variation of what you’ll find in most for loops.

要减小的值i被一个,重新分配i使得它成为i - 1i = i - 1 。 这种重新分配的简写是i-- ,这是您在大多数for循环中会发现的另一种变体。

In the bounceBall example above, we increased the variable i by one each time the code runs:

在上面的bounceBall示例中,每次代码运行时,我们将变量i增加一:

for (let i = 0; condition; i++) {   bounceBall() }

But should you increase or decrease i?

但是你应该增加还是减少i呢?

The answer lies in the condition. This condition statement evaluates either to true or false. If the statement evaluates to true, the statement runs.

答案在于条件 。 此条件语句的计算结果为truefalse 。 如果该语句的值为true ,则该语句运行。

When the statement has ran, JavaScript runs the increment expression and checks if the condition evaluates to true again. It repeats this process until the condition evaluates to false.

语句运行后,JavaScript运行增量表达式并检查条件是否再次为true 。 重复此过程,直到条件评估为false为止。

Once the condition evaluates to false, JavaScript skips the loop and moves on with the rest of your code.

一旦条件评估为false ,JavaScript将跳过循环,并继续处理其余代码。

So, if you do not want the loop to run, you can set a condition that evaluates to false immediately:

因此,如果您不希望循环运行,则可以设置一个条件,该条件的值立即为false:

// This loop will not run since the condition evaluates to false for (let i = 0; i < 0; i++) {   bounceBall()   const timesBounced = i + 1   console.log('The ball has bounced ' + timesBounced + ' times') }
// You will only see this console.log('next line of code')

If you want the loop to run twice, you change the condition such that it evaluates to false when the increment expression has run twice.

如果希望循环运行两次 ,则可以更改条件,以使增量表达式运行两次时其结果为false。

// This loop will run twice for (let i = 0; i < 2; i++) {   bounceBall()   const timesBounced = i + 1   console.log('The ball has bounced ' + timesBounced + ' times')") }
console.log('next line of code')

If you want the loop to run ten times, you change the condition such that it evaluates to false when the increment expression has run ten times.

如果希望循环运行十次 ,请更改条件,以使增量表达式运行十次后其结果为false。

// This loop will run ten times for (let i = 0; i < 10; i++) {   bounceBall()   const timesBounced = i + 1   console.log('The ball has bounced ' + timesBounced + ' times')") }
console.log('next line of code')

无限循环 (Infinite loops)

Infinite loops occur when the condition for your for loops always return true. Your browser will hang if you run an infinite loop.

for循环的条件始终返回true时,将发生无限循环。 如果运行无限循环,浏览器将挂起。

To recover from an infinite loop, you need to quit your browser forcefully. On a Mac, this means you right click on your browser icon and select “force quit.” On a Window’s machine, you open the Windows Task manager with ctrl + alt + del, select your browser, and click “End task.”

要从无限循环中恢复,您需要强行退出浏览器。 在Mac上,这意味着您右键单击浏览器图标,然后选择“强制退出”。 在Windows的计算机上,使用ctrl + alt + del打开Windows任务管理器,选择浏览器,然后单击“结束任务”。

遍历数组 (Looping through arrays)

In practice, you almost never write a loop that runs ten times like in the bounceBall example above. You’d always loop through an array or a object.

实际上,您几乎从不会编写像上面的bounceBall示例中那样运行十次的循环。 您将始终遍历数组或对象。

When you loop (or iterate) through an array, you go through each item in the array once. To do so, you can use the length or the array as a condition:

当您遍历(或迭代)数组时,将遍历数组中的每一项。 为此,可以使用长度或数组作为条件:

const fruitBasket = ['banana', 'pear', 'guava']
// fruitBasket.length is 3 for (let i = 0; i < fruitBasket.length; i++) {   console.log("There's a " + fruitBasket[i] + " in the basket") }
// => There's a banana in the basket // => There's a pear in the basket // => There's a guava in the basket

The alternate way to write this for loop is to use a negative increment expression. This version runs slightly faster than the for loop above, but loops the array from the end instead.

编写此for循环的另一种方法是使用负增量表达式。 该版本比上面的for循环运行速度稍快,但是从末尾开始循环数组。

for (let i = fruitBasket.length - 1; i >= 0; i--) {  console.log("There's a " + fruitBasket[i] + " in the basket") }
// => There's a guava in the basket // => There's a pear in the basket // => There's a banana in the basket

用“ for of”遍历数组 (Looping through arrays with “for of”)

Yet another (much better) way to loop through an array is to use a for...of loop. This is a new loop syntax that comes with ES6. It looks like this:

循环遍历数组的另一种方法(更好)是使用for...of循环。 这是ES6随附的新循环语法。 看起来像这样:

const fruitBasket = ['banana', 'pear', 'guava']
for (let fruit of fruitBasket) {   console.log(fruit) }
// => There's a banana in the basket // => There's a pear in the basket // => There's a guava in the basket

The for...of loop is preferable to the standard for loop because it always loops through the array once. There’s no need to write array.length, which makes your code much easier to read and maintain.

for...of循环优于标准的for循环,因为它总是循环遍历数组一次。 无需编写array.length ,这使您的代码更易于阅读和维护。

You can use for...of with any iterable object. These are objects that contain the Symbol.iterator property. Arrays are one such object. If you console.log an empty array, you’ll see that it has the Symbol.iterator as one of its keys (within the Array __proto__ key):

您可以将for...of用于任何可迭代的对象。 这些是包含Symbol.iterator属性的对象。 数组就是这样一种对象。 如果console.log一个空数组,您将看到它具有Symbol.iterator作为其键之一(在Array __proto__键内):

循环逻辑 (Logic in loops)

You can use if/else or any other logic within a for loop.

您可以在循环中使用if/else或任何其他逻辑。

For example, let’s say you have a list of numbers, and you want to create a second list of numbers that are smaller that 20.

例如,假设您有一个数字列表,并且想创建第二个小于20的数字列表。

To complete this objective, you first loop through the numbers.

为了完成这个目标,您首先要遍历数字。

const numbers = [25, 22, 12, 56, 8, 18, 34]
for (let num of numbers) {   // do something here }

Here, you want to check if each num is smaller than 20.

在这里,您要检查每个num是否小于20。

const numbers = [25, 22, 12, 56, 8, 18, 34]
for (let num of numbers) {   if (num < 20) {     // do something   } }

If num is smaller than 20, you want to add it to another array. To do so, you use the push method.

如果num小于20,则要将其添加到另一个数组中。 为此,您可以使用push方法。

const numbers = [25, 22, 12, 56, 8, 18, 34]let smallerThan20 = []
for (let num of numbers) {   if (num < 20) {     smallerThan20.push(num)   } }
// smallerThan20 === [12, 8 , 18]

结语 (Wrapping up)

A for loop is used when you want to execute the same task (or a set of tasks) multiple times.

如果要多次执行同一任务(或一组任务),则使用for循环。

You would rarely loop through code for exactly ten times. Normally, you’ll want to loop through an array instead.

您很少会遍历代码十次。 通常,您将需要遍历数组。

To loop through an array exactly once, you can use the for...of loop, which is much easier to write and understand compared to the traditional for loop.

要只遍历一次数组,可以使用for...of循环,与传统的for循环相比,它易于编写和理解。

Remember, you can write any amount of logic you want in loops. You can use functions, if/else statements, or even use loops in loops.

请记住,您可以在循环中编写任意数量的逻辑。 您可以使用函数, if/else语句,甚至可以在循环中使用循环。

If you loved this article, you’ll love learn Learn JavaScript — a course that helps you learn to build real components from scratch with Javascript. Click here to find out more about Learn JavaScript if you’re interested.

如果您喜欢这篇文章,那么您会喜欢学习JavaScript ,这是一门可以帮助您从头开始使用Javascript 构建实际组件的课程。 如果您有兴趣, 请单击此处以了解有关学习JavaScript的更多信息 。

(Oh, by the way, if you liked this article, I’d appreciate it if you could share it. ?)

(哦,顺便说一句,如果您喜欢这篇文章,如果可以分享的话 ,不胜感激。)

Originally published at zellwk.com.

最初在zellwk.com上发布。

翻译自: https://www.freecodecamp.org/news/javascript-essentials-how-to-wrap-your-head-around-for-loops-64e1a7248c9e/

JavaScript Essentials:如何为循环而烦恼相关推荐

  1. javascript中的for循环

    使用方法1: for(i=0;i<10;i++) { } 使用方法2:(可以对数据.对象成员等进行遍历) var y = [2, 3, 5];  for (i in y)        docu ...

  2. html中图片自动循环滚动代码,JavaScript代码实现图片循环滚动效果

    1.概述 循环滚动图片,不仅可以增添Web页面的动态效果,而且可以节省页面空间,有效地保证在有限的页面中显示更多的图片. 2.技术要点 主要应用setTimeout()方法实现图片的循环滚动效果.se ...

  3. JavaScript中利用for循环遍历数组

    这篇文章主要为大家详细介绍了JavaScript中利用for循环遍历数组,最好不要使用for in遍历,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 先看一段代码 1 2 3 4 5 6 7 8 ...

  4. django中的for循环_深入了解 JavaScript 中的 for 循环

    在ECMAScript5(简称 ES5)中,有三种 for 循环,分别是: 简单for循环 for-in forEach 在2015年6月份发布的ECMAScript6(简称 ES6)中,新增了一种循 ...

  5. JavaScript中for..in循环陷阱介绍

    for...in循环中的循环计数器是字符串,而不是数字它包含当前属性的名称或当前数组元素的索引,下面有个不错的示例大家可以参考下 大家都知道在JavaScript中提供了两种方式迭代对象:  (1)f ...

  6. linux数组删除数据,JavaScript在数组的循环中删除元素

    在开发JavaScript应用的过程中,经常会遇到在循环中移除指定元素的需求. 按照常规的思路,就是对数组进行一个for循环,然后在循环里面进行if判断,在判断中删除掉指定元素即可. 但是实际情况往往 ...

  7. JavaScript疑难杂症系列-事件循环

    javascript单线程 浏览器端,复杂的UI环境会限制多线程语言的开发. 例如,一个线程在操作一个DOM元素时,另一个线程需要去删除DOM元素, 这个之间就需要进行状态的同步,何况前端可能不止操作 ...

  8. php for循环in的用法,JavaScript中for in循环是如何使用的?需要注意些什么?

    大家都知道在JavaScript中提供了两种方式迭代对象: (1)for 循环: (2)for..in循环: 使用for循环进行迭代数组对象,想必大家都已经司空见惯了.但是,使用for.. in循环时 ...

  9. php event loop,理解javascript中的事件循环(Event Loop)

    背景 在研究js的异步的实现方式的时候,发现了JavaScript 中的 macrotask 和 microtask 的概念.在查阅了一番资料之后,对其中的执行机制有所了解,下面整理出来,希望可以帮助 ...

最新文章

  1. 一张图看懂中科大、国科大、中科院、社科院、上科大之间的关系
  2. 关于协作机器人10个观点的讨论
  3. ddos中的tcp反射攻击技术分析
  4. 技术文:微信小程序和服务器通信-WebSocket
  5. 前端实例练习 - 进度条
  6. 如何基于Restful ABAP Programming模型开发并部署一个支持增删改查的Fiori应用
  7. C# GDI+ 绘图
  8. redux-form V.7.4.2学习笔记(六)表单同步校验技术
  9. 圣诞抽奖 | 2018年的开发者,经历了裁员、加班种种不堪,2019年的你如何获得升职加薪的机会?...
  10. 机器学习笔记III: 基于支持向量机的分类预测
  11. CodeForces Round #191 (327C) - Magic Five 等比数列求和的快速幂取模
  12. c++小程序代码_# 微信小程序的原生框架和taro对比 ##
  13. android view state,Android状态系统(二)——View状态组合
  14. 如何自定义Mac锁屏界面消息?
  15. 蓝桥杯近三年初赛题之一(15年b组)
  16. 带宽、流量限制软件之Netlimiter Pro中文使用教程
  17. kubeadm安装部署k8s(1)
  18. 谷粒商城-商城业务(商品上架)
  19. 破解不加微信看朋友圈
  20. 盘点国内外25款备具代表性的协同办公软件

热门文章

  1. 最强整理!字节跳动历年Android中高级面试题全收录!附超全教程文档
  2. 【JavaScript】网站源码防止被人另存为
  3. 使用vue-cli脚手架搭建简单项目框架
  4. PrintJ的设计模式之旅——1.模式之父
  5. C#通过FFmpeg获得视频文件参数
  6. 内存墙,多核CPU的终结者?
  7. vs2005 vc++ 生成非托管的 不需要.net运行环境的exe程序方法
  8. RUNOOB python练习题33 使用join方法实现用逗号分隔列表
  9. 做一个vue的todolist列表
  10. 创梦天地通过聆讯:上半年经营利润1.3亿 腾讯持股超20%