JavaScript Essentials:如何為循環而煩惱

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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395009.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395009.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395009.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python中的類的成員變量以及property函數

1 python類的各種變量 1.1 全局變量 在類外定義的變量。 1.2 類變量 定義在類里面&#xff0c;所有的函數外面的變量。這個變量只有一份&#xff0c;是所有的對象共有的。在類外用“類.”來引用。 1.3 實例變量 用self.xxx在類的任何函數中定義的變量就是實例變量。在類內用“s…

C++常用的系統函數

數學<math.h>&#xff1a; 1 三角函數 double sin (double); double cos (double); double tan (double); 2 反三角函數 double asin (double); 結果介于[-PI/2, PI/2] double acos (double); 結果介于[0, PI] double atan (double); 反正切(主值), 結果介于[-PI/2, PI/2…

網頁特效java代碼,美化網頁常用特效代碼

1&#xff0e;讓文字不停地滾動&#xff1c;MARQUEE&#xff1e;滾動文字&#xff1c;/MARQUEE&#xff1e;2&#xff0e;記錄并顯示網頁的最后修改時間&#xff1c;script languageJavaScript&#xff1e;document.write("最后更新時間: " document.lastModified …

作業,兩次實驗

實驗一&#xff1a; 1 編程打印5行的倒三角形&#xff0c;第一行打印9個*&#xff0c;第二行7個*&#xff0c;……第5行打印1個* #include<stdio.h>int main(){printf("*********\n *******\n *****\n ***\n *\n");return 0;} 總結 注意換行以及位置的…

javaweb和ajax使用查詢出來的數據做下拉菜單_區塊鏈瀏覽器實用指南篇:利用鏈上數據把握減半行情...

進入2020年&#xff0c;加密貨幣市場最熱的話題當屬“減半”了。在減半行情的推動下&#xff0c;以BTC為首的減半幣種展現出了極強的上行趨勢。如何抓住這一波行情&#xff0c;評估正確時機&#xff1f;當然&#xff0c;這個問題的答案可以說是爭議紛紛&#xff0c;但有一個參考…

純函數式編程語言_純功能編程語言如何改變您的生活。

純函數式編程語言by Andrea Zanin由Andrea Zanin 純功能編程語言如何改變您的生活。 (How a purely functional programming language can change your life.) I believe everyone should learn Haskell, even if you won’t use it in your work. It’s beautiful, and it ch…

Win10 教育版

Windows 10 版本 1607 引入了專為 K-12 機構的特有需求而設計的兩個版本&#xff1a;Windows 10 專業教育版和 Windows 10 教育版。 這些版本為不斷發展的 K-12 教育 IT 環境提供特定于教育的默認設置。Windows 10 專業教育版Windows 10 專業教育版基于 Windows 10 專業版的商業…

java中的排序方法,Java中的排序比較方式:自然排序和比較器排序

這里所說到的Java中的排序并不是指插入排序、希爾排序、歸并排序等具體的排序算法。而是指執行這些排序算法時&#xff0c;比較兩個對象“大小”的比較操作。我們很容易理解整型的 i>j 這樣的比較方式&#xff0c;但當我們對多個對象進行排序時&#xff0c;如何比較兩個對象…

ImageView縮放選項

ImageView.ScaleType 將圖片邊界縮放到所在view邊界時的縮放選項。 Options for scaling the bounds of an image to the bounds of this view. 不同選項含義 CENTER 居中&#xff0c;不縮放。 Center the image in the view, but perform no scaling. CENTER_CROP 居中&#x…

css命名_CSS命名約定將節省您的調試時間

css命名I have heard lots of developers say they hate CSS. In my experience, this comes as a result of not taking the time to learn CSS.我聽到很多開發人員說他們討厭CSS。 以我的經驗&#xff0c;這是因為沒有花時間學習CSS。 Korean ??韓文?? ??: ??? ?…

電腦刪除快捷鍵_可能是知乎最有用的 Windows 快捷鍵學習指南。

在任何地方搜索“快捷鍵的使用”&#xff0c;你都能找到無數的列表清單。但你應該不會專門去對照一個個的表單&#xff0c;企圖把所有快捷鍵全部掌握吧&#xff1f;經過三年左右的總結和視頻制作&#xff0c;Topbook 大概產出了 20 支左右的快捷鍵、快捷操作及應用等相關的視頻…

java自動依照日期建表,腳本根據一個表中的日期字段填充每月匯總表

你想在這里做兩件事 . 我假設您正在使用Oracle(因為您正在使用Java) .首先&#xff0c;您希望對每個用戶的每日交易進行分組 .創建一個名為 tempTable 的臨時表 .使用 to_char(currentdate, yyyy/mm/dd) 對它們進行分組 .INSERT INTO tempTableSELECTuserid,resourceid,doc_nam…

算法專題 普及組【2008】三3 C++版

轉載于:https://www.cnblogs.com/qilinart/articles/5914850.html

linux用戶修改用戶shell

要拒絕系統用戶登錄,可以將其shell設置為/usr/sbin/nologin或者/bin/false # usermod -s /usr/sbin/nologin username 或者 # usermod -s /bin/false username /bin/false/bin/false什么也不做只是返回一個錯誤狀態,然后立即退出。將用戶的shell設置為/bin/false,用戶會無法登錄…

【覆蓋安裝】通用測試點

需要xmind文檔請留言將會私發。 轉載于:https://www.cnblogs.com/syw20170419/p/10457600.html

instagram架構_如何創建像Instagram這樣的照片共享應用程序:基本知識。

instagram架構by Dmytro Brovkin由Dmytro Brovkin 如何創建像Instagram這樣的照片共享應用程序&#xff1a;基本知識。 (How to create a photo sharing app like Instagram: the basics.) After two centuries of rapid development, photography has come a long way from b…

菜鳥裹裹電腦版_【綿陽最新轉讓】3500低價出售家用制氧機!東芝i5筆記本電腦、索尼微單相機、聯想筆記本電腦、奶茶店、服裝店轉讓......

轉換價值&#xff0c;傳承夢想西蜀網讓你淘好物~3500出售魚躍家用制氧機&#xff0c;帶霧化全新魚躍152021/9F_5W型家用制氧機&#xff0c;帶霧化。正規醫療器械公司買的&#xff0c;有小票&#xff0c;買到只用了一次&#xff0c;買成4382現低價轉讓。聯系電話&#xff1a;鄧女…

認識軟件性能測試10大誤區

曾經我們幫助客戶進行軟件性能測試的時候&#xff0c;客戶不解的問&#xff0c;不是必須通過功能測試后才可以測試性能嗎&#xff1f;可能有很多人會存在這樣的疑問&#xff0c;在這里&#xff0c;我們的多位專家根據多年經驗總結出性能測試的10大誤區&#xff0c;希望能給大家…

mac php oracle11g,Oracle11G函數整理

返回字符的字符函數 1、CHR(n) [n為正整數&#xff0c;如果ngt;256&#xff0c;就去MOD(n,256)] select CHR(65) a1,CHR(67)||CHR(65)||CHR(84) a2 FR返回字符的字符函數1、CHR(n) [n為正整數&#xff0c;如果n>256&#xff0c;就去MOD(n,256)]2、CONCAT(ch1,ch2) 拼接字符串…

軟工_個人博客作業3

PART1 博文閱讀感想 十幾篇博客一氣讀下來&#xff0c;有一個詞一直縈繞在我的腦海里——緊張&#xff01;緊張&#xff01;還是緊張&#xff01; 首先這緊張來自于自己的學習方面。作為計算機系的科班出身&#xff0c;當然與生俱來就有一種優越感——我們是專業的&#xff0c;…