Table of Contents
示例:
Home Web Front-end Front-end Q&A Does JavaScript have a for loop?

Does JavaScript have a for loop?

Mar 01, 2022 am 11:41 AM
for loop javascript

There is a for loop in JavaScript. The for loop in JavaScript language is used to execute code blocks multiple times. It is a commonly used loop tool in JS and is suitable for use when the number of loops is known; the syntax "for (initialization expression; conditional expression; variable update) { condition Code that is executed when the expression is true}".

Does JavaScript have a for loop?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

There is a for loop in JavaScript.

The for loop in JavaScript language is used to execute code blocks multiple times. It is the most commonly used loop tool in JavaScript and can also be used for array traversal loops, etc.

Why do we use for loop? For example, if we want the console to output all numbers between 1 and 1000, if we write the output statement alone, we have to write 1000 lines of code, but if we use a for loop, it can be achieved with just a few lines of code. In short, using for loops can make us write code more conveniently and quickly (of course, otherwise why would we need it).

JS for loop syntax

JS for loop is suitable for use when the number of loops is known. The syntax format is as follows:

for(初始化表达式; 条件表达式; 变量更新) {
	// 条件表达式为true时执行的代码
}
Copy after login
  • Initialization expression: usually used to declare the initial value of a counter, that is, the value at the beginning of the loop.

  • Conditional expression: Defines the condition for running the loop code block, which is used to control whether to execute the code in the loop body. If the condition is FALSE, the loop will exit immediately.

  • Variable update: executed after each loop code block is executed; each time the loop is executed, the counter value is immediately modified;

The execution flow of the for loop statement is shown in the figure below:

Does JavaScript have a for loop?

Example 1:

For example, in an HTML file, we write The following code implements calculation of the sum from 1 to 100:

  var result = 0;
  for(var i = 1; i <= 100; i++) {
    result = result + i;
  }
  alert(result);
Copy after login

When you open this file in the browser, a pop-up layer will pop up. The pop-up layer displays the sum from 1 to 100:


In the above code, we declare a variable result and assign it a value of 0, indicating that the initial sum is 0.

Then three statements in the for loop:

  • Variable initialization i = 1, which means starting from 1.
  • Conditional expression i <= 100 means that as long as i is less than or equal to 100, the loop will continue to execute. When i is greater than 100, the loop will continue. will stop.
  • Variable update i , we learned it before when we learned operators. This is the increment operator , which means that its operand is increased by 1.

At this point we can look at this for loop step by step:

第一次循环: result = 0 + 1   // 此时result值为0,  i的值为1
第二次循环: result = 1 + 2   // 此时result值为0+1,i的值为2
第三次循环: result = 3 + 3   // 此时result值为1+2,i的值为3
第四次循环: result = 6 + 4   // 此时result值为3+3,i的值为4
第五次循环: result = 10 + 5  // 此时result值为6+4,i的值为5
...
Copy after login

We just need to figure out the execution in the for loop The principle is that there is no need to manually calculate the sum. As long as the code is written, the computer will quickly tell us the sum from 1 to 100 after executing the code.

Let me add that in the above code, result = result i, we can also write result = i, which is the addition assignment operator we have learned before. do you remember?

Example 2:

Let’s look at another example. For example, we can use the for loop to implement array traversal. First define an array lst:

var lst = ["a", "b", "c", "d", "e"];
Copy after login

When writing the for loop, the first thing to do is to understand the three statements in the parentheses, because we can get it through the subscript index of the element in the array The value of the element, and the index of the array starts from 0, so the variable initialization can be set to i = 0. The second conditional expression, because the last index in the array is lst.length - 1, so as long as it is less than or equal to lst.length - 1, the loop will continue to execute. And i <= lst.length - 1 is equivalent to i<lst.length. The third variable is updated. Each time the loop loops, the index value is incremented by one, so it is i .

So the loop can be written like this:

for(i = 0; i<lst.length; i++){
    console.log(lst[i]);  // 输出数组中的元素值,从索引为0的值开始输出,每次加1,一直到lst.length-1
}
Copy after login

Output:

a
b
c
d
e
Copy after login

In fact, there is a better way to traverse the array, which is to use for... in loop statement to traverse the array.

The three expressions in the for loop

JS The three expressions in brackets in the for loop can be omitted, but use The semicolon that separates three expressions cannot be omitted, as shown in the following example:

// 省略第一个表达式
var i = 0;
for (; i < 5; i++) {
    // 要执行的代码
}
// 省略第二个表达式
for (var y = 0; ; y++) {
    if(y > 5){
        break;
    }
    // 要执行的代码
}
// 省略第一个和第三个表达式
var j = 0;
for (; j < 5;) {
    // 要执行的代码
    j++;
}
// 省略所有表达式
var z = 0;
for (;;) {
    if(z > 5){
        break;
    }
    // 要执行的代码
    z++;
}
Copy after login

for loop nesting

No matter which Loops can be nested (that is, one or more loops are defined within a loop). Let's take the for loop as an example to demonstrate the nested use of loops:

for (var i = 1; i <= 9; i++) {
    for (var j = 1; j <= i; j++) {
        document.write(j + " x " + i + " = " + (i * j) + "&emsp;");
    }
    document.write("<br>");
}
Copy after login

Running results:

Does JavaScript have a for loop?

扩展知识:for 循环变体--for…in 循环

for...in 循环主要用于遍历数组或对象属性,对数组或对象的属性进行循环操作。for...in 循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。

语法如下:

for (变量 in 对象) {
	// 代码块
}
Copy after login

for 循环括号内的变量是用来指定变量,指定的可以是数组对象或者是对象属性。

示例:

使用 for...in 循环遍历我们定义好的 lst 数组:

var lst = ["a", "b", "c", "d", "e"];for(var l in lst){
    console.log(lst[l]);}
Copy after login

输出:

a
b
c
d
e
Copy after login

除了数组,for...in 循环还可以遍历对象,例如我们遍历 侠侠 的个人基本信息:

var object = {
    姓名:&#39;侠侠&#39;,
    年龄:&#39;22&#39;,
    性别:&#39;男&#39;,
    出生日期:&#39;1997-08-05&#39;,
    职业:&#39;程序员&#39;,
    特长:&#39;跳舞&#39;
}

for(var i in object) {
	console.log(i + ":" + object[i]);
}
Copy after login

输出:

姓名: 侠侠
年龄: 22
性别: 男
出生日期: 1997-08-05
职业:程序员
特长:跳舞
Copy after login

【相关推荐:javascript学习教程

The above is the detailed content of Does JavaScript have a for loop?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles