適合初學者的 JavaScript 循環:學習基礎知識
這是一個陰沉的星期一,而你正在工作。我們都知道周一有多令人沮喪,對吧?你的老闆走近你並說:“嘿,我周末收到了300 封未打開的電子郵件。我希望你打開每一封,寫下發件人的姓名,並在完成後刪除這些電子郵件。”
如果您嘗試手動執行此任務,看起來會很累。您想到的下一件事可能是在 Google 上尋找可以自動化此流程並讓您的生活更輕鬆的軟體,對吧?
嗯,我們在程式設計上也有類似的情況。有時您需要重複執行任務直到完成。你如何解決這個問題?在 JavaScript 中,我們有所謂的循環。循環使我們能夠透過減少完成任務所需的程式碼量來解決重複的任務。
在本文中,我們將討論什麼是循環、它是如何運作的,以及我們可以在程式中應用它的各種方法。
什麼是循環?
JavaScript 中使用迴圈來輕鬆執行重複操作。它們基於傳回 true 或 false 的條件。
條件是必須傳遞以保持循環運行的表達式。當指定條件傳回 true 值時,循環運行;當傳回 false 值時,循環停止。
什麼時候需要使用循環?
循環對於執行重複性任務很有用。例如,使用循環可以縮短解決問題所需的程式碼。它可以節省時間、優化記憶體使用並提高靈活性。
循環的真正意義不僅在於減少程式碼長度和限制重複。它們在處理數組、物件或其他結構中的資料時也很有幫助。此外,循環透過減少重複程式碼和提高程式碼可重複使用性來促進程式碼模組化,這使得創建可在專案的不同部分中使用的程式碼成為可能。
循環類型
循環有兩大類:入口控制循環和出口控制循環。
入口控制循環在執行循環體之前評估「循環入口」的條件。如果條件為真,身體就會運作。如果沒有,身體就不會運作。 for 和 while 迴圈是入口控制迴圈的範例。
退出控制 循環重點在於測試條件上的循環體,確保在評估測試條件之前循環體至少執行一次。退出控制循環的一個很好的例子是 do-while 循環。
讓我們來看一些入口控制循環的範例:
while 循環
while 迴圈有以下語法。
while (condition) { // loop's body }
以下列表解釋了 while 迴圈的功能:
- while 迴圈採用括號內的測試條件。
- 程式檢查條件以查看它是通過還是失敗。
- 只要滿足條件,循環體內的程式碼就會執行。
- 一旦測試條件失敗,程式就會終止運作。
下面,我們來看一個 while 迴圈的實際範例:
let arr = []; let i = 1; let number = 5; while (i <= number) { arr.push(i) i++ }
console.log(arr)
- 上面的程式碼片段初始化了「arr」、「i」和「num」變數。
- 「arr」變數是一個數組,保存通過測試條件的值。
- 「i」變數在每次迭代後追蹤每個增量。
- 每次迭代後,「number」變數會將「i」的值與其值 (5) 進行比較。
- 只要“i”小於或等於“number”,循環體中的程式碼就會在每次迭代後將“i”的每個值推入數組。
- 一旦「i」的目前值不符合條件,在這種情況下,「i」的值大於「number」(6),循環就會停止運作。
push() 方法是一個內建的 JavaScript 函數,它將新項目新增到陣列的末端。
輸出
[1, 2, 3, 4, 5]
do while 循環
do-while 迴圈與 while 迴圈非常相似; while 和 do-while 迴圈之間的主要區別在於,do-while 迴圈確保在評估迴圈條件之前至少執行一次程式碼,do-while 迴圈具有以下語法。
do { // loop's body } while (//condition)
do-while 是退出控制循環的一個很好的例子。這是因為退出控制循環在測試條件之前優先考慮循環體,現在讓我們深入研究一個利用 do-while 循環的實際程式碼範例。
範例:
let i = 1; let num = 5; do { console.log(i); i++; } while (i <= num);
現在讓我們先分解這段程式碼:
- We initialized the "i" and "num" variables.
- The console logs in the value of "i" (1) before evaluating the loop's condition.
- The condition is checked, and the value of "i" increments with +1 after each iteration.
- The loop ends its operation once "i" is greater than "num".
Output
1 2 3 4 5
Although the do-while loop is very much similar to the while loop, there are subtle differences we must note, let’s take another example that compares the difference between the while and do-while loop.
let i = 5; let num = 4 while( i < num) { console.log(i) }
This while loop above won't return any result to the console, now why is this so?
- We initialized the "i" and "num" variables with values of 5 and 4, respectively.
- The condition checks if the value of "i" is less than "num".
- If true, it logs in each respective value.
- Since the initial value of "i" exceeds that of "num", the loop never runs.
now let's take a similar example with the do-while loop.
let i = 5; let num = 4; do { console.log(i) } while ( i < num)
Output
5
The do-while loop ensures the execution of the code block, which returns 5 into the console, although "i" has a higher value than "num" initially, it's still logged in the console once. This representation shows you the difference in functionality between the do-while and while loop.
For loop
The for loop is a unique type of loop and one of the most commonly used loop by programmers, the for loop is a loop that runs a code block for a specific number of time depending on a condition. The for loop has the following syntax below.
for (Expression1...; Expression2....; Expression3...{ //code block }
Expression1: This part of a for loop is also known as the initialization area, it's the beginning of our for loop and the area where the counter variable is defined; the counter variable is used to track the number of times the loop runs and store that as a value.
Expression2: This is the second part of the loop, this part defines the conditional statement that would execute the loop.
Expression3: This is where the loop ends; the counter variable in this section updates its value after each iteration either by increasing or decreasing the value as specified in the condition.
Let's dive into an example using the for loop.
for (let i = 0; i < 100; i++) { console.log("Hello World" ) }
From the code snippet above, let's break it down together.
- First, we've initialized the counter variable "i" with a value of zero.
- Next, we've created the conditional statement that would keep the code running.
- We compared the value of "i" with 100, if it passes this test, "Hello World" is logged.
- This process repeats while the counter increases with +1 after each iteration.
- The loop ends once the counter's value reaches 100.
Output
Hello World Hello World Hello World ... //repeated 97 more times making it 100 "Hello World" in total ...
for-each loop
The for-each loop is a method in JavaScript that travels through an array and applies a callback function on each element in that array; a callback function is simply another function passed as a parameter into a function, the callback function works by running sequentially after the main function is done executing.
Let's examine the basic syntax of a for-each loop.
array.forEach(function(currentValue, index, arr))
The provided code above explains the workings of a for-each loop.
- This loop accepts three parameters, which are the current value, an index, and an array.
- The current value represents the present value of the element in the array.
- The index is an optional parameter that tells you the numbered position of the current element in that array.
- The arr is another optional parameter that tells you what array the element belongs to.
let myArray = [1, 2, 3, 4, 5]; array.forEach((num, index, arr) => { arr[index] = num * 2; console.log(array); });
Let's break down the example above:
- We initialized an array with the variable name "myArray" and stored it with integers ranging from 1 to 5.
- The for-each array method takes three parameters and applies a callback function on the array.
- This line; arr[index] = num * 2 multiplies the value of the current element by 2 and assigns the returned value to the current element's index.
Take note, the for-each array method does not return a new array; rather, it modifies the original array and returns it.
Output
[2, 4, 6, 8, 10]
What are for... in and for... of loops in JavaScript?
The for... in and for... of loops are very useful when it comes to iterating over iterable objects, iterable objects refers to any element that is capable of being looped over, common examples of iterables objects are arrays, strings, sets, etc.
The for... in and for... of are similar in how they iterate/move through objects, the main difference between them is shown on how they return values.
for... in loops
A for... in loop is useful when you need to extract the key(s)/properties from an object and it corresponding properties from the parent object, the for... in loop at times might iterate through an object in a manner that is different from the way it was defined in that particular object, let's take an example of a for... in loop in action.
let namesArray = []; const studentScores = { John: 60, Dan: 53, Tricia: 73, Jamal: 45, Jane: 52 } for(const name in studentScores){ namesArray.push(name); } console.log(namesArray);
In the example above, we have defined an object named studentScores that contains several student names and their corresponding scores, by using for... in, we were able to retrieve only the names of the students, which represent the keys of the object studentScores, and store them in an array by using the push() method.
Output
["John", "Dan", "Tricia", "Jamal", "Jane"]
for... of loops
The for... of loop is a special type of loop that iterates over the values of iterable objects such as arrays, strings, maps, e.t.c., for... of loops does not concern itself with the keys or properties of an object, rather it shows priorities on the values only, the for... of loop is unable to iterate over regular objects and will throw an error since they are not iterable. Let's take an example using the for.. of loop.
let numArray = [1,2,3,4,5] for (const value of numArray) { console.log(value) }
// Output = 1,2,3,4,5
In summary, the for... in and for... of loops are great way to loop through iterable objects, the main difference is a for... in loop returns the key of an Object while the for... of loop returns only the values of iterable objects.
What is an infinite loop and how can we avoid it?
An infinite loop refers to a loop that continues to run indefinitely; this occurs when a loop has no defined exit condition. Infinite loops are dangerous because they can crash your browser and lead to unwanted actions in your program.
// infinite loop sample
while (true) {
console.log("keep on running")
}
To prevent infinite loops in your program, always ensure that there is an exit condition defined within your loop.
Conclusion
Thank you very much for getting to the end of this article, loops in Javascript are important concept every developer needs to master as it is very valuable to creating a good and optimizable program, I believe with this article you would be able to understand the basics and intricacies of using loops in your program.
以上是適合初學者的 JavaScript 循環:學習基礎知識的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。
