Table of Contents
Array iteration method
forEach()
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.
every
some
Home Web Front-end JS Tutorial Detailed analysis of iteration methods in Javascript arrays

Detailed analysis of iteration methods in Javascript arrays

Sep 11, 2018 pm 03:31 PM
javascript

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(&#39;li&#39;);
    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);
})
Copy after login

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])
}
Copy after login

Finally, let’s take a look at the compatibility of the forEach() method, directly above.

##YesYes1.59YesYes
ChromeEdgeFirefoxInternet ExplorerOperaSafari
map()

This method executes the given function on each element of the array and returns a new array. The result of the new array is the result of executing the method on the elements in the original array.

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.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]
Copy after login
In our daily development work, we will encounter a lot of data formatting processes. Using these methods can greatly facilitate our processing.

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>
});
Copy after login

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}]
Copy after login
Of course we are actually The data complexity at work is far more than this, but we can clearly feel the advantages of these methods for processing data.
Finally, let’s take a look at the compatibility of the map() method, as shown in the picture above.

ChromeEdgeFirefoxInternet ExplorerOperaSafari##Yesfilter
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]
Copy after login

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);
Copy after login

Finally, let’s take a look at the compatibility of the filter() method, directly above.

Chrome##YesYes1.59YesYes

every

该方法是对数组的每一个元素执行给定的函数,
如果数组中的每个元素都满足给定的条件则返回 true,否则返回 false。

该方法接受两个参数,一个是元素每一项执行的回调函数,一个是可选参数,回调函数运行时 this 的值。

传入的回调函数会接受三个参数分别是:数组中的元素(item),元素的索引(index,可选),数组本身(array,可选)。

//语法
var newArrs = array.every(callback[, this])
var newArrs = array.every(callback(item, index, array){
    //执行方法
});

//例子
var number = [2, 3, 4, 5, 6];
var result1 = number.every(item => item > 4);
console.log(result1); //false
var result2 = number.every(item => item > 1);
console.log(result2); //true
Copy after login

我们在来看看 every() 方法的兼容性,直接上图。

EdgeFirefoxInternet ExplorerOperaSafari
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
Copy after login

我们在来看看 some() 方法的兼容性,直接上图。

Chrome Edge Firefox Internet Explorer Opera Safari
Yes Yes 1.5 9 Yes Yes
可以看出 every 方法是全部返回 true 时,整个函数才返回 true;some 方法则是全部返回 false 时,整个函数才返回 false。

相关推荐:

javascript中Array数组的迭代方法实例分析_javascript技巧

JavaScript数组的5种迭代方法实例详解

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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

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

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

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