Home > Web Front-end > JS Tutorial > Detailed analysis of iteration methods in Javascript arrays

Detailed analysis of iteration methods in Javascript arrays

不言
Release: 2018-09-11 15:31:21
Original
1118 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template