search
HomeWeb Front-endFront-end Q&ADoes JavaScript have a for loop?

Does JavaScript have a for loop?

Mar 01, 2022 am 11:41 AM
for loopjavascript

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时执行的代码
}
  • 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);

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 means that as long as <code>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
...

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"];

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 is equivalent to <code>i<lst.length>. The third variable is updated. Each time the loop loops, the index value is incremented by one, so it is <code>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
}

Output:

a
b
c
d
e

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++;
}

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>");
}

Running results:

Does JavaScript have a for loop?

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

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

语法如下:

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

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

示例:

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

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

输出:

a
b
c
d
e

除了数组,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]);
}

输出:

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

【相关推荐: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
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
The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft