Home  >  Article  >  CMS Tutorial  >  Mastering JavaScript: Part 3, Exploring Loops

Mastering JavaScript: Part 3, Exploring Loops

WBOY
WBOYOriginal
2023-08-28 22:37:091241browse

掌握 JavaScript:第 3 部分,探索循环

Suppose you are tasked with writing a program that displays the numbers 1 to 100. One way to accomplish this is to write 100 console.log() statements. But I'm sure you won't, because you'll get tired of line nine or line ten.

The only part that changes in each statement is the number, so there should be a way to write just one statement. There are also loops. Loops let us repeat a set of steps within a block of code.

  • While Loop
  • Do-While Loop
  • For Loop
  • Array
  • For-Of Loop
  • For-In Loop

While Loop

A While Loop will repeatedly execute a set of statements when some condition evaluates to true. When the condition is false, the program exits the loop. This kind of loop tests a condition before executing the iteration. Iteration is the execution of the loop body. Here is a basic example of a while loop:

let x = 10;

while(x > 0) {
   console.log(`x is now ${x}`);
   x -= 1;
}

console.log("Out of the loop.");

/* Outputs:
x is now 10
x is now 9
x is now 8
x is now 7
x is now 6
x is now 5
x is now 4
x is now 3
x is now 2
x is now 1
Out of the loop. */

In the example above, we first set x to 10. In this example, the condition x > 0 evaluates to true, so the code within the block is executed. This prints the statement "x is now 10" and decrements the value of x by one. During the next check, x equals 9, which is still greater than 0. And so the cycle continues. On the last iteration, x ends up being 1, and we print "x is now 1". Afterwards, x becomes 0, so the condition we are evaluating no longer holds true. Then, we start executing the statements outside the loop and print "Out of theloop".

This is the general form of a while loop:

while (condition) {
    statement;
    statement;
    etc.
}

One thing to remember when using while loops is not to create a never-ending loop. This happens because the condition never becomes false. If it happens to you, your program will crash. Here is an example:

let x = 10;

while(x > 0) {
   console.log(`x is now ${x}`);
   x += 1;
}

console.log("Out of the loop.");

In this case, we are increasing x instead of decreasing it, and the value of x is already greater than 0, so the loop will continue indefinitely.

Task

How many times will this loop be executed?

let i = 0;

while (i < 10) {
    console.log("Hello, World");
    i += 1;
}

Do-While Loop

The do-while loop will execute the statement body first and then check the condition. This kind of loop is useful when you know you want to run the code at least once. The following example will log the value of x once, even though the condition evaluates to false because x is equal to 0.

let x = 0;

do {
   console.log(`x is now ${x}`);
   x -= 1;
} while(x > 0);

console.log("Out of the loop.");

/* Outputs:
x is now 0
Out of the loop. */

I've used do-while loops many times in my own projects to generate random values ​​and then continue generating them as long as they don't meet certain conditions. This helps avoid duplication due to initialization and intra-loop reallocation.

This is the general form of a do-while loop:

do {
    statement;
    statement;
    etc.
} while (condition);

Task

Write a do-while loop to display the numbers 1 to 10.

For Loop

The for loop will repeat a block of code a specific number of times. The following example shows the numbers 1 through 10:

for (let i = 1; i <= 10; i++) {
    console.log(i);
}

This is the general form of a for loop:

for (initial; condition; step) {
    statement;
    statement;
    etc.
}

Initial is an expression that sets the value of a variable. This is an optional expression that performs initialization.

Condition is an expression that must be true to execute the statement. The statements within the block are executed only if the condition evaluates to true. Skipping the conditions entirely will cause them to always be true, so you have to exit the loop some other way.

step is an expression that increments the value of a variable. This is also optional and is executed after all statements within the for block have executed. Step expressions are often used near the end condition of a loop.

You can also write a for loop as the equivalent while loop. All you need to do is change your statements and conditions slightly. The for loop above can be rewritten as:

initial;

while(condition) {
    statement;
    statement;
    etc.
    step;
}

One programming pattern is to use a for loop to update the value of a variable with the variable itself and the new value. This example adds the numbers 1 through 10:

let x = 0;

for (let i = 1; i <= 10; i++) {
    x += i;
}

// Outputs: 55
console.log(x);

This is the equivalent while loop which gives the same output:

let x = 0;
let i = 1;

while(i <= 10) {
  x += i;
  i += 1;
}

// Outputs: 55
console.log(x);

You should notice how I increment at the end of the while block instead of at the beginning. Increasing the loop variable i at the beginning would give us 65, which is not what we intend to do here.

The = operator is an assignment operator that adds a value back to a variable. Here is a list of all assignment operators:

操作员 示例 等效
+= x += 2  x = x + 2
-= x -= 2 x = x - 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
%= x%=2 x = x % 2

任务

编写一个 for 循环来计算数字的阶乘。数字n的因子是从1到n的所有整数的乘积。例如,4! (4 阶乘)为 1 x 2 x 3 x 4,等于 24。

数组

数组是一个包含项目列表的对象,这些项目称为元素,可以通过索引进行访问。索引是元素在数组中的位置。第一个元素位于索引 0 处。

数组有一个名为 length 的属性,它为您提供数组中元素的总数。这意味着您可以创建一个 for 循环来迭代数组中的项目,如下所示:

let arr = [1, 2, "Hello", "World"];

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

/*
Outputs:
1
2
Hello
World
*/

二维数组是指元素为数组的数组。例如:

let arr = [
    [1, 2],
    ["Hello", "World"]
];

这是循环数组并显示每个元素的方式:

for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
        console.log(arr[ i ][ j ]);
    }
}

/*
Outputs:
1
2
Hello
World
*/

您将如何重写上面的循环,以便从末尾开始打印数组元素?

For-Of 循环

迭代数组时最常见的场景之一是从头开始,然后一次遍历所有元素,直到到达末尾。有一种更短的方法可以将 for 循环编写为 for-of 循​​环。

for-of 循​​环让我们可以循环遍历可迭代对象(例如数组、映射和字符串)的值。 for-of 循​​环基本上用于迭代对象的属性值。这是上一节中的循环,重写为 for-of 循​​环。

let arr = [1, 2, "Hello", "World"];

for (let item of arr) {
    console.log(item);
}

/*
Outputs:
1
2
Hello
World
*/

循环字符串:

let big_word = "Pulchritudinous";

for (let char of big_word) {
    console.log(char);
}

/*
Outputs:
P
u
l
c
h
r
i
t
u
d
i
n
o
u
s
*/

For-In 循环

这种循环让我们可以循环访问对象的属性。对象是一种将键映射到值的数据结构。 JavaScript 中的数组也是对象,因此我们也可以使用 for-in 循环来循环数组属性。我们首先看看如何使用 for-in 循环来迭代对象键或属性。

以下是使用 for-in 循环遍历对象键的示例:

let obj = {
    foo: "Hello",
    bar: "World"
};

for (let key in obj) {
    console.log(key);
}

/*
Outputs:
foo
bar
*/

下面是使用 for-in 循环遍历数组的示例:

let arr = [1, 2, "hello", "world"];

for (let key in arr) {
    console.log(arr[key]);
}

/* Outputs:
1
2
hello
world */

我想补充一点,即使我们能够使用 for-in 循环遍历数组元素,您也应该避免这样做。这是因为它的目的是循环访问对象的属性,如果您只想循环数组索引来获取数组值,则在某些情况下可能会得到意外的结果。

评论

循环让我们减少代码中的重复。 While 循环让我们重复一个动作,直到条件为假。 do-while 循环将至少执行一次。 For 循环让我们重复一个动作,直到到达计数结束。 for-in 循环的设计是为了让我们可以访问对象中的键。 for-of 循​​环的设计是为了让我们能够获取可迭代对象的值。

在下一部分中,您将学习函数。

本文已根据 Monty Shokeen 的贡献进行了更新。 Monty 是一位全栈开发人员,他也喜欢编写教程和学习新的 JavaScript 库。

The above is the detailed content of Mastering JavaScript: Part 3, Exploring Loops. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn