javascript
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:
它分為四個部分initialExpression , condition , incrementalExpression和statement :
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 - 1與i = 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.
答案在于條件 。 此條件語句的計算結果為true或false 。 如果該語句的值為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 basketThe 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 basketThe 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:如何为循环而烦恼的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到大树倒了什么意思
- 下一篇: 梦到两个头的蛇是什么意思