search
HomeWeb Front-endJS TutorialWhat are the main loops in javascript

The main loops of JavaScript are: 1. for loop; 2. "for...in" loop; 3. map method; 4. forEach loop; 5. filter filter loop; 6. Object.keys traversal properties of the object.

What are the main loops in javascript

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 loop should be the most common and the most used loop traversal method, so its readability and ease of maintenance are relatively poor, but it You can break out of the loop in time.

let arr = [1,2,3,4,5,6,7]for(let i = 0;i<arr.length;i++){
  console.log(arr[i])
}// 1,2,3,4,5,6,7

2. for...in

The for...in loop is mainly aimed at traversing objects. When you want to obtain the corresponding key value of the object, use for...in It is still more convenient

//针对对象来说  
//任何对象都继承了Object对象,或者其它对象,继承的类的属性是默认不可遍历的,
//for... in循环遍历的时候会跳过,但是这个属性是可以更改为可以遍历的,那么就会造成遍历到不属于自身的属性。
//结合使用hasOwnProperty方法,在循环内部判断一下,某个属性是否为对象自身的属性。否则就可以产生遍历失真的情况。
let obj = {name: &#39;xiaohua&#39;, sex: &#39;male&#39;, age: &#39;28&#39;}
for(let key in obj){
    if(obj.hasOwnProperty(key)){
        console.log(obj[key])
    }
}

3. map

The map method passes all members of the array into the parameter function in turn, and then returns the results of each execution into a new array. 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]

The map method accepts a function as a parameter. When this function is called, the map method passes it three parameters: the current member, the current position, and the array itself.

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

4. 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 the loop cannot be stopped in the middle. It will always Traverse all members

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

5. Filter filter loop

The filter method is used to filter array members, and the members that meet the conditions form a new array and return it. Its parameter is a function. All array members execute the function in sequence, and the members whose return result is true form a new array and return it. This method does not change the original array.

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}]

The filter method in the Array class in ECMAScirpt5 is used to remove all "false" type elements (false, null, undefined, 0, NaN 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 is a function that traverses the elements in the array and returns true or false according to the true or false type of the element.

6. Object.keys traverses the properties of the object

Object The parameter of the .keys method is an object and returns an array. The members of this array are all property names of the object itself (not inherited), and only enumerable properties are returned.

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

To determine whether an object is an empty object, you can use Object.keys(obj).length>0

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What are the main loops in javascript. 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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools