Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true
or false
when analysed. A loop will continue running until the defined condition returns false
.
JavaScript中使用循环来根据条件执行重复的任务。 分析后,条件通常返回true
或false
。 循环将继续运行,直到定义的条件返回false
为止。
The three most common types of loops are
三种最常见的循环类型是
You can type js for
, js while
or js do while
to get more info on any of these. Let's look at them, and some variations, in more detail now.
您可以键入js for
, js while
还是js do while
得到任何的这些详细信息。 现在,让我们更详细地查看它们以及一些变体。
for循环 (for loop)
句法 (Syntax)
for ([initialization]); [condition]; [final-expression]) {
// statement
}
The javascript for
statement consists of three expressions and a statement:
javascript for
语句包含三个表达式和一个语句:
描述 (Description)
- initialization - Run before the first execution on the loop. This expression is commonly used to create counters. Variables created here are scoped to the loop. Once the loop has finished it’s execution they are destroyed. 初始化-在第一次执行循环之前运行。 此表达式通常用于创建计数器。 此处创建的变量的作用域是循环。 循环完成后,将销毁它们。
- condition - Expression that is checked prior to the execution of every iteration. If omitted, this expression evaluates to true. If it evaluates to true, the loop’s statement is executed. If it evaluates to false, the loop stops. 条件-在每次迭代执行之前检查的表达式。 如果省略,则此表达式的值为true。 如果计算结果为true,则执行循环语句。 如果评估为假,则循环停止。
- final-expression - Expression that is run after every iteration. Usually used to increment a counter. But it can be used to decrement a counter too. final-expression-每次迭代后运行的表达式。 通常用于递增计数器。 但是它也可以用于减少计数器。
- statement - Code to be repeated in the loop 语句-在循环中重复的代码
any of these three expressions or the statement can be omitted. For loops are commonly used to count a certain number of iterations to repeat a statement. Use a break
statement to exit the loop before the condition expression evaluates to false.
这三个表达式中的任何一个或该语句都可以省略。 For循环通常用于计算一定数量的迭代以重复一条语句。 在条件表达式评估为false之前,使用break
语句退出循环。
常见陷阱 (Common Pitfalls)
Exceeding the bounds of an array
超出数组的范围
When indexing over an array many times it is easy to exceed the bounds of the array (ex. try to reference the 4th element of a 3 element array).
多次索引数组时,很容易超出数组的范围(例如,尝试引用3元素数组的第4个元素)。
// This will cause an error.
// The bounds of the array will be exceeded.
var arr = [ 1, 2, 3 ];
for (var i = 0; i <= arr.length; i++) {
console.log(arr[i]);
}
output:
1
2
3
undefined
There are two ways to fix this code. Set the condition to either i < arr.length
or i <= arr.length - 1
有两种方法可以修复此代码。 将条件设置为i < arr.length
或i <= arr.length - 1
例子 (Examples)
Iterate through integers from 0-8
循环访问0到8之间的整数
for (var i = 0; i < 9; i++) {
console.log(i);
}
output:
0
1
2
3
4
5
6
7
8
Break out of a loop before condition expression is false
在条件表达式为假之前跳出循环
for (var elephant = 1; elephant < 10; elephant+=2) {
if (elephant === 7) {
break;
}
console.info('elephant is ' + elephant);
}
output:
elephant is 1
elephant is 3
elephant is 5
对于...在循环 (for...in loop)
The for...in
statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
for...in
语句以任意顺序遍历对象的可枚举属性。 对于每个不同的属性,可以执行语句。
for (variable in object) {
...
}
Required/OptionalParameterDescriptionRequiredVariableA different property name is assigned to variable on each iteration.OptionalObjectObject whose enumerable properties are iterated.
Required / OptionalParameterDescriptionRequiredVariable每次迭代都会为变量分配一个不同的属性名称。OptionalObjectObject会迭代其可枚举的属性。
例子 (Examples)
// Initialize object.
a = { "a": "Athens", "b": "Belgrade", "c": "Cairo" }
// Iterate over the properties.
var s = ""
for (var key in a) {
s += key + ": " + a[key];
s += "<br />";
}
document.write (s);
// Output:
// a: Athens
// b: Belgrade
// c: Cairo
// Initialize the array.
var arr = new Array("zero", "one", "two");
// Add a few expando properties to the array.
arr["orange"] = "fruit";
arr["carrot"] = "vegetable";
// Iterate over the properties and elements.
var s = "";
for (var key in arr) {
s += key + ": " + arr[key];
s += "<br />";
}
document.write (s);
// Output:
// 0: zero
// 1: one
// 2: two
// orange: fruit
// carrot: vegetable
// Efficient way of getting an object's keys using an expression within the for-in loop's conditions
var myObj = {a: 1, b: 2, c:3}, myKeys = [], i=0;
for (myKeys[i++] in myObj);
document.write(myKeys);
//Output:
// a
// b
// c
for ... of循环 (for...of loop)
The for...of
statement creates a loop iterating over iterable objects (including Array, Map, Set, Arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
for...of
语句创建一个循环,循环访问可迭代对象(包括Array,Map,Set,Arguments对象等),并为每个不同属性的值调用要执行的语句的自定义迭代挂钩。
for (variable of object) {
statement
}
DescriptionvariableOn each iteration a value of a different property is assigned to variable.objectObject whose enumerable properties are iterated.
描述variable在每次迭代中,将不同属性的值分配给variable.objectObject,其可枚举属性被迭代。
例子 (Examples)
数组 (Array)
let arr = [ "fred", "tom", "bob" ];
for (let i of arr) {
console.log(i);
}
// Output:
// fred
// tom
// bob
地图 (Map)
var m = new Map();
m.set(1, "black");
m.set(2, "red");
for (var n of m) {
console.log(n);
}
// Output:
// 1,black
// 2,red
组 (Set)
var s = new Set();
s.add(1);
s.add("red");
for (var n of s) {
console.log(n);
}
// Output:
// 1
// red
参数对象 (Arguments object)
// your browser must support for..of loop
// and let-scoped variables in for loops
function displayArgumentsObject() {
for (let n of arguments) {
console.log(n);
}
}
displayArgumentsObject(1, 'red');
// Output:
// 1
// red
while循环 (while loop)
The while loop starts by evaluating the condition. If the condition is true, the statement(s) is/are executed. If the condition is false, the statement(s) is/are not executed. After that, while loop ends.
while循环通过评估条件开始。 如果条件为真,则执行该语句。 如果条件为假,则不执行该语句。 之后,while循环结束。
Here is the syntax for while loop:
这是while循环的语法 :
句法: (Syntax:)
while (condition)
{
statement(s);
}
statement(s): A statement that is executed as long as the condition evaluates to true.
statement(s):只要条件评估为真,就执行该语句。
condition: Here, condition is a Boolean expression which is evaluated before each pass through the loop. If this condition evaluates to true, statement(s) is/are executed. When condition evaluates to false, execution continues with the statement after the while loop.
condition:这里的condition是一个布尔表达式,在每次通过循环之前都会对其求值。 如果此条件的值为真,则执行语句。 当条件评估为false时,将在while循环之后继续执行该语句。
例: (Example:)
var i = 1;
while (i < 10)
{
console.log(i);
i++; // i=i+1 same thing
}
Output:
1
2
3
4
5
6
7
8
9
如何使用JavaScript While循环进行迭代 (How to Iterate with JavaScript While Loops)
While loops will run as long as the condition inside the ( ) is true. Example:
只要()中的条件为true,就会运行while循环。 例:
while(condition){
code...
}
Hint 1:
提示1:
Use a iterator variable such as i in your condition
在您的条件下使用迭代器变量(例如i)
var i = 0;
while(i <= 4){
}
扰流板预警解决方案! (Spoiler Alert Solution Ahead!)
Solution:
解决方案 :
// Setup
var myArray = [];
// Only change code below this line.
var i = 0;
while (i <= 4){
myArray.push(i);
i++;
}
做... while循环 (Do...while loop)
The do...while
loop is closely related to while
loop. In the do while loop, the condition is checked at the end of the loop.
do...while
循环与while
循环密切相关。 在do while循环中,条件在循环结束时检查。
Here is the syntax for do...while
loop:
这是do...while
循环的语法 :
句法: (Syntax:)
do {
*Statement(s);*
} while (*condition*);
statement(s): A statement that is executed at least once before the condition or Boolean expression is evaluated and is re-executed each time the condition evaluates to true.
语句:在对条件或布尔表达式求值之前至少执行一次的语句,并在每次条件求值为true时重新执行。
condition: Here, a condition is a Boolean expression. If Boolean expression evaluates to true, the statement is executed again. When Boolean expression evaluates to false, the loops ends.
condition:这里的条件是布尔表达式 。 如果布尔表达式的计算结果为true,则再次执行该语句。 当布尔表达式的计算结果为false时,循环结束。
例: (Example:)
var i = 0;
do {
i = i + 1;
console.log(i);
} while (i < 5);
Output:
1
2
3
4
5
如何使用JavaScript进行迭代……循环 (How to Iterate with JavaScript Do…While Loops)
Do...While
loops makes sure that the code is executed at least once, and after the execution, if the condition inside thewhile()
is true, it continues with the loop, otherwise it stop.Do...While
循环确保代码至少执行一次,并且在执行之后,如果while()
内部的条件为true ,那么它将继续循环,否则将停止。
Solution:
解:
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while(i <= 10);
翻译自: https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/