这是一个阴沉的星期一,而你正在工作。我们都知道周一有多令人沮丧,对吧?你的老板走近你并说:“嘿,我周末收到了 300 封未打开的电子邮件。我希望你打开每一封,写下发件人的姓名,并在完成后删除这些电子邮件。”
如果您尝试手动执行此任务,看起来会很累。您想到的下一件事可能是在 Google 上寻找可以自动化此过程并让您的生活更轻松的软件,对吧?
嗯,我们在编程中也有类似的情况。有时您需要重复执行任务直到完成。你如何解决这个问题?在 JavaScript 中,我们有所谓的循环。循环使我们能够通过减少完成任务所需的代码量来解决重复的任务。
在本文中,我们将讨论什么是循环、它是如何工作的,以及我们可以在程序中应用它的各种方法。
JavaScript 中使用循环来轻松执行重复操作。它们基于返回 true 或 false 的条件。
条件是必须传递以保持循环运行的表达式。当指定条件返回 true 值时,循环运行;当返回 false 值时,循环停止。
循环对于执行重复性任务很有用。例如,使用循环可以缩短解决问题所需的代码。它可以节省时间、优化内存使用并提高灵活性。
循环的真正意义不仅仅在于减少代码长度和限制重复。它们在处理数组、对象或其他结构中的数据时也很有帮助。此外,循环通过减少重复代码和提高代码可重用性来促进代码模块化,这使得创建可在项目的不同部分中使用的代码成为可能。
循环有两大类:入口控制循环和出口控制循环。
入口控制循环在执行循环体之前评估“循环入口”的条件。如果条件为真,身体就会运行。如果没有,身体就不会运行。 for 和 while 循环是入口控制循环的示例。
退出控制 循环重点关注测试条件上的循环体,确保在评估测试条件之前循环体至少执行一次。退出控制循环的一个很好的例子是 do-while 循环。
让我们看一些入口控制循环的示例:
while 循环具有以下语法。
while (condition) { // loop's body }
以下列表解释了 while 循环的功能:
下面,我们来看一个 while 循环的实际例子:
let arr = []; let i = 1; let number = 5; while (i <= number) { arr.push(i) i++ }
console.log(arr)
push() 方法是一个内置的 JavaScript 函数,它将新项目添加到数组的末尾。
输出
[1, 2, 3, 4, 5]
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);
现在让我们分解一下这段代码:
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?
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.
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.
Output
Hello World Hello World Hello World ... //repeated 97 more times making it 100 "Hello World" in total ...
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.
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:
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]
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.
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"]
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.
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.
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中文网其他相关文章!