search
HomeCMS TutorialWordPressMastering JavaScript: Part 3, Exploring Loops

掌握 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
Can I learn WordPress in 3 days?Can I learn WordPress in 3 days?Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

Is WordPress a CMS?Is WordPress a CMS?Apr 08, 2025 am 12:02 AM

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

What is the WordPress good for?What is the WordPress good for?Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Should I use Wix or WordPress?Should I use Wix or WordPress?Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How much does WordPress cost?How much does WordPress cost?Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Is WordPress still free?Is WordPress still free?Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

Is WordPress easy for beginners?Is WordPress easy for beginners?Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress?Why would anyone use WordPress?Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment