Detailed analysis of iteration methods in Javascript arrays
This article brings you a detailed analysis of the iteration method in Javascript arrays. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
We have introduced some usage of arrays. For example: how does an array behave the same as a "stack", what method is used to behave the same as a "queue", etc. Because there are many array methods in Javascript, we do not introduce too many things in one article. Next, let’s learn about other functions of arrays
It’s officially started!
Array iteration method
The array iteration method is very frequently used in our development projects, very important, and very efficient. Not only that, these methods can also make our code It will be very concise, so to speak, and it will be terrible if you don't use these methods often in development.
For example, how do we add DOM nodes in batches
let containerUl = document.getElementById('container'); let li; let peoples = [{name: 'Liu', age: 14}, {name: 'Li', age: 13}, {name: 'Cao', age: 11}]; //for 循环 for (let i = 0; i < peoples.length; i++) { li = document.createElement('li'); li.innerHTML = peoples[i].name + ":" + peoples[i].age; containerUl.appendChild(li); }; //数组的迭代方法,更加简洁 peoples.forEach((people) => { li = document.createElement('li'); li.innerHTML = people.name + ":" + people.age; containerUl.appendChild(li); })
The above is just a simple example. In fact, our daily development process is much more than this, and it is much more complicated than this. Therefore, how to carry out work development efficiently is very necessary. Let’s start with the more commonly used ones one by one.
forEach()
This method executes the given function on each element of the array and returns undefined (or no return value).
This method accepts two parameters, one is the callback function executed by each element, and the other is an optional parameter, the value of this when the callback function is run.
The callback function passed in will accept three parameters: the element in the array (item), the index of the element (index, optional), and the array itself (array, optional).
//语法 array.forEach(callback[, this]) array.forEach(callback(item, index, array){ //函数体,执行的操作 }); //看个例子,本质上与 for 循环一样 let items = ['a', 'b', 'c']; items.forEach(function (item) { console.log(item); }); for (let i = 0; i < items.length; i++) { console.log(items[i]) }
Finally, let’s take a look at the compatibility of the forEach() method, directly above.
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Yes | 1.5 | 9 | Yes | Yes |
//语法 var newArrs = array.map(callback[, this]) var newArrs = array.map(callback(item, index, array){ //return 执行后的结果 }); //例子 let numbers = [1, 2, 3]; let newNumbers = numbers.map(x => x * x); console.log(newNumbers); //[1, 4, 9]
For example, the process of converting a class array into an array
<ul> <li><input type="text" value="1"></li> <li><input type="text" value="2"></li> <li><input type="text" value="3"></li> </ul> <script> let list = document.getElementsByTagName('input'); let newList = Array.prototype.map.call(list, item => { return item.value; }); console.log(newList);//[1,2,3] </script> });
For example, the data required for formatting
let peoples = ['Liu', 'Cao', 'Pan']; let peoplesInfo = peoples.map(people => { return { name: people, age: Math.floor(Math.random()*20) } }); console.log(peoplesInfo); // [{name: Liu, age: XX}, // {name: Cao, age: XX}, // {name: Pan, age: XX}]
Edge | Firefox | Internet Explorer | Opera | Safari | |
---|---|---|---|---|---|
Yes | 1.5 | 9 | Yes | Yes |
This method also executes the given function on each element of the array and returns a new array. An array is made up of items each of which returns true. To put it simply, it is to filter out what we want.
This method accepts two parameters, one is the callback function executed by each element, and the other is an optional parameter, the value of this when the callback function is run.
The callback function passed in will accept three parameters: the element in the array (item), the index of the element (index, optional), and the array itself (array, optional).
//语法 var newArrs = array.filter(callback[, this]) var newArrs = array.filter(callback(item, index, array){ //return 满足条件的项 }); //例子 let numbers = [1, 2, 3, 4, 5]; let newNumbers = numbers.filter(x => x > 2); console.log(newNumbers); //[3, 4, 5]
The "filter" method also has many functions in practical work. For example, we find out which children are among a group of people.
var peoples = [{name: 'liu', age: 9}, {name: 'jiang', age: 18}, {name: 'cao', age: 20}, {name: 'pan', age: 3}]; var childrens = peoples.filter(people => people.age < 10); console.log(childrens);
Finally, let’s take a look at the compatibility of the filter() method, directly above.
Edge | Firefox | Internet Explorer | Opera | Safari | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1.5 | 9 | Yes | Yes |
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Yes | Yes | 1.5 | 9 | Yes | Yes |
some
该方法是对数组的每一个元素执行给定的函数,
如果数组中的有一个元素满足条件则返回 true,如果全部不满足条件则返回 false。
该方法接受两个参数,一个是元素每一项执行的回调函数,一个是可选参数,回调函数运行时 this 的值。
传入的回调函数会接受三个参数分别是:数组中的元素(item),元素的索引(index,可选),数组本身(array,可选)。
//语法 var newArrs = array.some(callback[, this]) var newArrs = array.some(callback(item, index, array){ //执行方法 }); //例子 var number = [2, 3, 4, 5, 6]; var result1 = number.some(item => item < 1); console.log(result1); //false var result2 = number.some(item => item > 5); console.log(result2); //true
我们在来看看 some() 方法的兼容性,直接上图。
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Yes | Yes | 1.5 | 9 | Yes | Yes |
相关推荐:
javascript中Array数组的迭代方法实例分析_javascript技巧
The above is the detailed content of Detailed analysis of iteration methods in Javascript arrays. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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
