Loops
JavaScript Loops: while and for
While writing a program, you can meet a situation when you need to execute an action repeatedly. In that case, you would need to write loop statements, which let us reduce the number of lines. In other words, loops offer a quick and easy way to do something repeatedly. (在编写程序时,您可能会遇到需要反复执行操作的情况。在这种情况下,您需要编写循环语句,这样我们就可以减少行数。换句话说,循环提供了一种快速简单的方法来重复做某事。)
For example, if you want to type a ‘Welcome to w3cdoc’ message 100 times in your webpage, instead of copying and pasting the same line 100 times, you can use loops, you can complete this task in 3 or 4 lines. (例如,如果要在网页中键入“欢迎使用w3cdoc”消息100次,而不是复制和粘贴同一行100次,则可以使用循环,可以用3行或4行完成此任务。)
There are five kinds of tools that JavaScript supports:
while (期间)
do…while (ɏһ¼¶)
for ( 为了 )
for…in (- for… in)
for…of (- for… of)
Let’s discuss each of these loop statements in detail. (让我们详细讨论这些循环语句中的每一个。)
The “while” loop
The “while” loop (“while”循环)
The “while” loop is the most fundamental loop in JavaScript. The while loop executes its statement or code block repeatedly as long as a specified condition is true. Once the expression becomes false, the loop ends. (“while”循环是JavaScript中最基本的循环。while循环重复执行其语句或代码块,只要指定的条件为真。表达式变为false后,循环结束。)
The syntax for while (While的语法)
while (condition) {
// code
// so-called "loop body"
}
The code from the loop body will be executed as soon as the condition is truthy. In the example below the loop outputs i while i < 10:
let i = 0;
while (i < 10) { // shows 0, then 1, then 2, … ,then 9
console.log(i);
i++;
}
There are three iterations (repeat) that loop makes in the example above. Iteration means a single execution of the loop body. (在上面的示例中,循环进行了三次迭代(重复)。迭代意味着循环体的单次执行。)
If i++ was missing from the presented above example, the loop would repeat forever. But the browser provides ways to stop such loops. Any variable or expression can be a loop, which is evaluated and converted to a boolean by while. (如果上述示例中缺少i + + ,则循环将永远重复。但浏览器提供了阻止此类循环的方法。任何变量或表达式都可以是循环,通过while计算并转换为布尔值。)
Example of a shorter way to write while (i != 0):
let i = 10;
while (i) { // the loop stops when i becomes 0 and the condition becomes false
console.log(i);
i--;
}
Curly braces are not needed for a single-line body. In case the loop body has a single statement, we can forget the curly braces {…}:
let i = 10;
while (i) console.log(i--);
The “do…while” loop
The “do…while” loop (“do… while”循环)
The do…while loop has some similarities with while loop except that in do…while loop the block of code performed once even before checking the condition. It means that the do…while statement repeats until a specified condition evaluates to false. (Do… while循环与while循环有一些相似之处,除了in do… while循环甚至在检查条件之前执行一次代码块。这意味着do… while语句重复,直到指定的条件评估为false。)
We can move the condition check below the loop body using the do…while syntax:
do {
// loop body
} while (condition);
The loop will execute the body first, then after checking the condition will execute it again and again in case it is truthy. (循环将首先执行body ,然后在检查条件后将一次又一次地执行它,以防它是真实的。)
For example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
You can use this form of syntax when you want the body of the loop to execute at least once nevertheless of the condition being truthy. Usually, the other form is preferred: while(…) {…}.
The “for” loop
The “for” loop (“for”循环)
The for loop repeats a block of code since a specified condition evaluates to false. (For循环重复代码块,因为指定的条件评估为false。)
The for loop is used to execute a block of code for a certain number of times. (For循环用于执行一定次数的代码块。)
It is more complex, but also the most commonly used loop, which looks like this:
for (begin; condition; step) {
// ... loop body ...
}
The for loop is the most solid form of looping that includes the following three important parts:
The loop initialization is used to initialize the counter variables and executed first even before the loop begins. It is used to assign values to variables that will be used inside the loop. (-循环初始化用于初始化计数器变量,甚至在循环开始之前首先执行。它用于将值分配给将在循环内使用的变量。)
The condition expression is evaluated at the beginning of every iteration. The loop statement executes if it evaluates to true, and the for loop ends if it evaluates to false. (-条件表达式在每次迭代开始时计算。如果loop语句的计算结果为true ,则执行该语句;如果for循环的计算结果为false ,则结束。)
Increment is used to update the loop counter with a new value each time the loop runs. (-增量用于每次循环运行时使用新值更新循环计数器。)
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum = sum + i;
}
console.log("Sum = " + sum); // => Sum = 55
The “for…in” loop
The “for…in” loop (“for… in”循环)
The for…in loop is a special type of a loop that iterates a specified variable over the properties of an object. JavaScript executes the specified statements for each distinct property. (For… in循环是一种特殊类型的循环,它在对象的属性上迭代指定的变量。JavaScript为每个不同的属性执行指定的语句。)
for…in is a method that used for iterating over “enumerable” properties of an object and applies to all objects that have these properties. (for… in是一种方法,用于迭代对象的“可枚举”属性,并应用于具有这些属性的所有对象。)
An enumerable property is a property of an object that has an Enumerable value of true. So a property is “enumerable”, if it is enumerable. By calling property.enumerable we can see if a property is enumerable. It will return true or false. (可枚举属性是Enumerable值为true的对象的属性。因此,如果属性是可枚举的,则它是“可枚举的”。通过调用property.enumerable ,我们可以查看属性是否可枚举。它将返回true或false。)
The for…in loop is used with the following syntax :
Syntax:
for (variableName in Object) {
// Code to be executed
}
The variable in the for…in loop is not a number but string, which involves the name of the current property or the index of the current array element. (For… in循环中的变量不是数字,而是字符串,它涉及当前属性的名称或当前数组元素的索引。)
The “key” for value in an Array is the numerical index that is essentially enumerable properties. (数组中value的“键”是本质上是可枚举属性的数值索引。)
This means that we can loop over all the values in an Array by bringing back their index using the for..in Array. (这意味着我们可以通过使用数组中的for..返回其索引来循环数组中的所有值。)
const arr = ['a', 'b', 'c', 'd'];
for (const index in arr) {
console.log(arr[index])
} // Result: a, b, c, d
But it is generally advised that for…in method can’t be used with arrays, because there is no guarantee that the iteration happens in sequence, which is usually important for arrays. (但通常建议for… in方法不能与数组一起使用,因为无法保证迭代按顺序进行,这通常对数组很重要。)
In this example you can see how to loop through all properties of a JavaScript object. If we want to loop through and console.log all the values in this Object, we can do the following :
let obj = {
a: 'a',
b: 'b',
c: 'c',
d: 'd',
}
for (let key in obj) {
console.log(obj[key])
} // Result: a, b, c, d
The characters in a string have indexes. So the indexes are enumerable properties (like Arrays) that just happen to be integers. (字符串中的字符具有索引。因此,索引是可枚举的属性(如数组) ,恰好是整数。)
let string = 'Welcome to w3cdoc';
for (let index in string) {
console.log(string[index])
} // Result: W, e, l, c, o, m, e, ,t, o, ,W, 3, D, o, c, s
The for…of Loop
The for…of Loop (The for… of Loop)
The for…of statement creates a loop which allows to iterate over arrays or other iterable objects (such as Arrays, Strings, Maps, Sets and so on)very easily. (For… of语句创建了一个循环,允许非常轻松地迭代数组或其他可迭代对象(如数组、字符串、映射、集合等)。)
for…of method is used for iterating over “iterable collections” that are objects that have a [Symbol.iterator] property. (for… of方法用于迭代具有[Symbol.iterator]属性的“可迭代集合”。)
With a [Symbol.iterator] property we can easily iterate over the collection by calling the Symbol.iterator.next() method to get back the next item in the collection. (使用[Symbol.iterator]属性,我们可以通过调用[Symbol.iterator] () .next ()方法轻松迭代集合,以获取集合中的下一个项目。)
The for…of syntax is wrapping around the [ [Symbol.iterator] to create loops and it uses the following syntax :
for (variable of iterable) {
// code block to be executed
}
let arr = ['a', 'b', 'c', 'd'];
for (let item of arr) {
console.log(item)
}
// Result: a, b, c, d
Example for of loop through strings:
for..of and Objects
for..of and Objects (for.. of和Objects)
for…of (for… of)
Objects
[Symbol.iterator]
for..of and Arrays/Strings
for..of and Arrays/Strings (for.. of和数组/字符串)
The for…of loop works rather well with Arrays and Strings, because they are iterable. This method is a good way of looping through an Array in sequence. (For… of循环适用于数组和字符串,因为它们是可迭代的。此方法是按顺序循环数组的好方法。)
Example for of loop through arrays:
let string = 'Welcome to w3cdoc';
for (let character of string) {
console.log(character)
} // Result: W, e, l, c, o, m, e, ,t, o, ,W, 3, D, o, c, s
Breaking the loop
Breaking the loop (打破循环)
When the condition of loop becomes falsy it exits, but we can force the exit just using the special break directive. (当循环条件变为假时,它退出,但我们可以使用特殊break指令强制退出。)
In this example the loop asks the user for a series of numbers, “breaking” when no number is entered:
for (let i = 1; i <= 10; i++) {
if (i == 6) break;
console.log(i);
} // Result: 1, 2, 3, 4, 5
Example of the nested for loops:
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (j === 2) {
i = 5;
break;
}
}
console.log(i);
} // Result: 5
Continue to the next iteration
Continue to the next iteration (继续下一个迭代)
We call the continue directive a “lighter version” of break, which does not stop the whole loop. But it stops the current iteration and if the condition allows it forces the loop to start a new one. (我们将continue指令称为break的“较轻版本” ,它不会停止整个循环。但它会停止当前迭代,如果条件允许,它会强制循环开始新的迭代。)
The loop in this example uses continue to output only odd values:
for (let i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
console.log(i); // Result: 1, 3, 5, 7, 9
}
The continue directive stops executing the body for values of i and passes control to the next iteration of for. That is why the alert is only called for odd values. (Continue指令停止执行i值的正文,并将控制传递给for的下一次迭代。这就是为什么仅对奇数值调用警报的原因。)
The continue directive helps decrease nesting
The continue directive helps decrease nesting (Continue指令有助于减少嵌套)
A loop that shows odd values looks like this:
for (let i = 1; i <= 10; i++) {
if (i % 2) {
console.log(i); // Result: 1, 3, 5, 7, 9
}
}
This is identical to the example above from a technical point of view. We can just cover the code in an if block instead of using continue. But this created one more level of nesting. The long code inside of may decrease the readability. (从技术角度来看,这与上述示例相同。我们可以只覆盖if块中的代码,而不是使用continue。但这又创造了一个层次的嵌套。里面的长代码可能会降低可读性。)
No break/continue to the right side of ‘?’
No break/continue to the right side of ‘?’ (没有中断/继续到“?”的右侧)
We cannot use syntax constructs that are not expressions with the ternary operator ?. Directives such as break/continue are not allowed there. (>我们不能使用不是三元运算符?的表达式的语法构造。此处不允许使用中断/继续等指令。)
So if we take this code:
if (i > 10) {
console.log(i);
} else {
continue;
}
…and rewrite it using a question mark, it will stop working: there will be a syntax error. It is another reason not to use the question mark operator ? instead of if.
(i > 10) ? console.log(i): continue; // continue isn't allowed here