search
HomeWeb Front-endFront-end Q&AWhat types of javascript loop statements are there?

What types of javascript loop statements are there?

Jul 16, 2021 pm 04:08 PM
javascriptloop statement

Loop statements include: 1. for loop; 2. "for...in" loop; 3. while loop; 4. "do...while" loop; 5. forEach loop; 6. map; 7 , filter filter loop; 8. "Object.keys" traverses the properties of the object.

What types of javascript loop statements are there?

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

In project development, no matter which framework it is based on, data processing is necessary, and processing data is inseparable from various traversal loops. There are many ways to loop through in JavaScript. Here are some common js loops.

1. for loop

The for statement is mainly used to execute a loop that determines the number of executions.

The basic syntax of the for statement is as follows:

for([初始值表达式];[条件表达式];[增量表达式]){
   循环体语句;
}

Description:

  • "Initial value expression": Set the initial value for the loop variable;

  • "Conditional expression": As the basis for whether to enter the loop, it can be any expression, but it is generally a relational expression or a logical expression, and the value is true or false. Each time before executing the loop, the conditional expression value will be judged. If the value is true (the value is true or non-0 or non-empty), the loop body statement is executed; otherwise, the loop is exited and the code after the loop statement is executed;

  • "Increment expression Expression": Update the value of the loop variable based on this expression.

Any of the above three expressions can be omitted, but it should be noted that; in for() cannot be omitted. So if all three expressions are omitted, the for statement becomes: for(;;){loop body statement}. What needs to be noted at this time is that if there is no statement to exit the loop within the loop body, it will enter an infinite loop.

Example:

     var sum = 0;
     for(var i = 1; i <= 100;i++){        //在for语句中使用var声明循环变量,使代码更简洁
         sum += i;
     }
     alert("1~100的累加和sum=" + sum);

2. for...in

##The for...in loop is mainly aimed at traversing objects. When you want to get the corresponding key value of an object, it is more convenient to use for...in

var a = [1, 2, ,,,,,,true,,,,,,, "a",,,,,,,,,,,,,,,4,,,,,56,,,,,,"b"];  //定义数组
var b = [], num = 0;
for (var i = 0; i < a.length; i ++) {  //遍历数组
    if (typeof a[i] == "number")  //如果为数字,则返回该元素的值
        b.push(a[i]);
    num ++;  //计数器
}
console.log(num);  //返回42,说明循环了42次
console.log(b);  //返回[1,2,4,56]

3. While loop

The while statement is the most commonly used A loop statement that is often used in programs to execute loops based on conditions without caring about the number of loops.

while 语句的基本语法如下:
while(条件表达式){
     循环体;
}

Explanation:

  • Conditional expression: It is a loop control condition and must be placed in parentheses. It can be any expression, but it is generally a relational expression or A logical expression that evaluates to true or false. Note: Values ​​that are true, non-0, and non-null are all true values, otherwise they are false values.

  • Loop body: represents an operation that needs to be performed repeatedly. It can be a simple statement or a compound statement. When it is a simple statement, the braces {} can be omitted, otherwise the braces {} must be used.

When the while statement is executed, it first judges the value of the conditional expression. If it is true, the loop body statement is executed, and then the conditional expression is judged. If the value is still true, , then continue to execute the loop body statement; otherwise, execute the statement after the while statement. If the value of the expression is false the first time it is evaluated (either false or 0 or null, etc.), the body of the loop will not be executed even once.

It should be noted that in order for the while loop to end normally, there should be statements in the loop body that modify the loop conditions or other statements to terminate the loop. Otherwise, the while loop will enter an infinite loop, that is, it will continue to execute in a loop. Loop body.

For example, the following loop statement will cause an infinite loop.

var i=1,s=0;
whiel(i<=5){
    s+=i;      
}

The initial value of i in the above code is 1. Since the value of the i variable is not modified in the loop body, the expression iInfinite loops will greatly occupy system resources and may eventually cause the system to crash, so we must pay attention to avoid infinite loops when programming.

     var sum = 1, i = 1;
     var ex = 1;
     while(sum <= 1.5){
         sum += 1/((i + 1)*(i + 1));
         if(sum > 1.5)
              break;
         i++;
         ex +=" + 1/(" + i + "*" + i + ")";
     }
     alert("表达式的值小于等于1.5时的i=" + i + ",对应的表达式为:" + ex);

4. do...while loop

The do...while statement is a variation of the while statement. The difference between the two is that the while statement places the loop condition judgment before the execution of the loop body statement, while the do...while statement puts the loop condition judgment after the execution of the loop body statement.

The basic syntax of the do...while statement is as follows:

do{
  循环体;
}while (条件表达式);

The meanings of "conditional expression" and "loop body" are the same as those of the while statement. What needs to be noted here is that the do...while statement needs to end with;. If it is not added in the code, JavaScript will automatically add it.

When the do...while statement is executed, the loop body statement is first executed, and then the value of the conditional expression is judged. If the value is true (the value is true or a non-zero value), the loop body statement is executed again. The do...while statement will execute the loop body at least once, which is significantly different from the while statement.

     var sum = 1, i = 1;
     var ex = 1;
     do{
         sum += 1/((i + 1)*(i + 1));
         if(sum > 1.5)
              break;
         i++;
         ex +=" + 1/(" + i + "*" + i + ")";
     }while(sum <= 1.5);
     alert("表达式的值小于等于1.5时的i=" + i + ",对应的表达式为:" + ex);

5. forEach

The method of using forEach is similar to the method of using map, except that the forEach method does not return a value, it is only used to operate data, and it cannot be used in the middle of the loop. Stopped, all members will always be traversed

let arrObj = [{
    id: 1,
    name: &#39;xiaohua&#39;
},{
    id:2,
    name: &#39;xiaomin&#39;
},{
    id:3,
    name: &#39;xiaobai&#39;
}]
arrObj.forEach((item,index,arr)=>{
    console.log(arr) // arrObj
    console.log(index)  // 0 1 2
    console.log(item.name) // xiaohua xiaomin xiaobai
})

6. map

The map method passes all the members of the array into the parameter function in turn, and then passes each The execution results are composed into a new array and returned.

The loop cannot be stopped in the middle, and all members will always be traversed

let arr = [1,2,3,4,5]
let arr2 = arr.map((n)=>{
      return n+1
})
console.log(arr2) // [2,3,4,5,6]
console.log(arr) // [1,2,3,4,5]

map方法接受一个函数作为参数。该函数调用时,map方法向它传入三个参数:当前成员、当前位置和数组本身。

let arrObj = [{
    id: 1,
    name: 'xiaohua'
},{
    id:2,
    name: 'xiaomin'
},{
    id:3,
    name: 'xiaobai'
}]
arrObj.map((item,index,arr)=>{
    console.log(arr) // arrObj
    console.log(index)  // 0 1 2
    console.log(item.name) // xiaohua xiaomin xiaobai
})

七、filter过滤循环

filter方法用于过滤数组成员,满足条件的成员组成一个新数组返回。它的参数是一个函数,所有数组成员依次执行该函数,返回结果为true的成员组成一个新数组返回。该方法不会改变原数组。

let arrObj = [{
    id: 1,
    name: &#39;xiaohua&#39;
},{
    id:2,
    name: &#39;xiaomin&#39;
},{
    id:3,
    name: &#39;xiaobai&#39;
}]
let arr2 = arrObj.filter((item,index,arr)=>{
    return (item.name === &#39;xiaohua&#39;)
})
console.log(arr2)  // [{id:1,name:&#39;xiaohua}]

 ECMAScirpt5 中 Array 类中的 filter 方法使用目的是移除所有的 ”false“ 类型元素  (falsenullundefined0NaN or an empty string):

let arr = [3, 4, 5, 2, 3, undefined, null, 0, ""];
let arrNew = arr.filter(Boolean);
console.log(arrNew)  //  [3, 4, 5, 2, 3]

Boolean 是一个函数,它会对遍历数组中的元素,并根据元素的真假类型,对应返回 true 或 false.

八、Object.keys遍历对象的属性

Object.keys方法的参数是一个对象,返回一个数组。该数组的成员都是该对象自身的(而不是继承的)所有属性名,且只返回可枚举的属性。

let obj = {name: 'xiaohua', sex: 'male', age: '28'}
console.log(Object.keys(obj))
// ["name", "sex", "age"]

判断一个对象是否是空对象,可以用Object.keys(obj).length>0

【推荐学习:javascript高级教程

The above is the detailed content of What types of javascript loop statements are there?. 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
Frontend Development with React: Advantages and TechniquesFrontend Development with React: Advantages and TechniquesApr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React vs. Other Frameworks: Comparing and Contrasting OptionsReact vs. Other Frameworks: Comparing and Contrasting OptionsApr 17, 2025 am 12:23 AM

React is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.

Demystifying React in HTML: How It All WorksDemystifying React in HTML: How It All WorksApr 17, 2025 am 12:21 AM

React operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.

React in Action: Examples of Real-World ApplicationsReact in Action: Examples of Real-World ApplicationsApr 17, 2025 am 12:20 AM

React is widely used in e-commerce, social media and data visualization. 1) E-commerce platforms use React to build shopping cart components, use useState to manage state, onClick to process events, and map function to render lists. 2) Social media applications interact with the API through useEffect to display dynamic content. 3) Data visualization uses react-chartjs-2 library to render charts, and component design is easy to embed applications.

Frontend Architecture with React: Best PracticesFrontend Architecture with React: Best PracticesApr 17, 2025 am 12:10 AM

Best practices for React front-end architecture include: 1. Component design and reuse: design a single responsibility, easy to understand and test components to achieve high reuse. 2. State management: Use useState, useReducer, ContextAPI or Redux/MobX to manage state to avoid excessive complexity. 3. Performance optimization: Optimize performance through React.memo, useCallback, useMemo and other methods to find the balance point. 4. Code organization and modularity: Organize code according to functional modules to improve manageability and maintainability. 5. Testing and Quality Assurance: Testing with Jest and ReactTestingLibrary to ensure the quality and reliability of the code

React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

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.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function