Home > Web Front-end > JS Tutorial > body text

Iteration usage of Array in JavaScript

一个新手
Release: 2017-09-19 10:48:11
Original
1199 people have browsed it

Iteration of Array

I like studying JavaScript, which is much more interesting than looking at HTML and CSS. Without further ado, let’s comprehensively introduce the five iteration methods of JavaScript’s array type. We strive to be comprehensive, with simple and complex examples for each method.

  • every() method, each item returns true, returns true

  • some() Method, one item returns true, returns true

  • filter() method, returns an array, each element returns true

  • map() method returns an array, each element is the result of calling the function

  • forEach( ) method, does not return results, each item runs a specific function


Why should we use these iterations? I am just lazy and don’t like to write for loops. The above Every method can be done using for. So the driving force generated by technology is laziness. I like iteration to make the code look awesome. I recently looked at the syntax of ES6, which is called simplicity, and it is almost like a bible. However, it also increases the difficulty of reading the code. Among the above five methods, the commonly used ones are map() and forEach(). Let’s start with forEach.

1. forEach()

This thing is just a for loop. Just put what you want to do in parentheses and it will not return any results. Take a look at the definition:

Definition: The forEach() method is used to call each element of the array and pass the element to the callback function.

 语法:
array.forEach(function(currentValue, index, arr), thisValue)
Copy after login

Note:

  • forEach() will not execute the callback function for an empty array

  • does not return the result. If it is taken, it will be undefined. Try the following

  • In the end, the original array will not be changed

It takes a long time to explain, just encapsulate the for loop. Not all languages ​​have similar methods. PHP also has a similar method called foreach. Here is a simple example.

        var num = [1, 2, 3, 4, 5];
        num.forEach((value) => {            
        console.log(value);
        });
Copy after login

Traverse the array and print each element. What he does is no different from for. An anonymous function is used here (ES6 arrow function, just a function), and then a function is written to be called explicitly, and the position is also passed in.

        function myFunc(item, index) {
            console.log(index, item);
        }        var num = [1, 2, 3, 4, 5];
        num.forEach(myFunc);
Copy after login

Iteration usage of Array in JavaScript

The front is the position, and the back is the value. There is nothing to explain in the code. One parameter is the optional thisValue. To put it bluntly, it specifies which this in the called function is. The default is undefined.

thisValue Optional. The value passed to the function generally uses the "this" value. If this parameter is empty, "undefined" will be passed to the "this" value.

It is more clear to give an example, the code explains everything.

        function myFunc(item, index) {
            console.log(this.value, index, item);
        }        var num = [1, 2, 3, 4, 5];        
        var obj = {value: '就是一个对象而已'};
        num.forEach(myFunc, obj);
Copy after login

Iteration usage of Array in JavaScript

A very silly piece of code that simply uses the value of the incoming object in each iteration. This in the function is the object obj passed in. Everything that needs to be explained has been explained. One more thing, this product can replace for, but it is not absolute. In terms of efficiency, the for loop is still faster than it. As mentioned in the essence of JavaScript language, I will not go into details here.

2. map()

This product is much more useful than the previous one. It can be seen in many JS frameworks, such as React and Redux. Regarding the reducer function, it is required to return A new state object cannot modify the original state object, just use it to return.

Definition: The map() method returns a new array, and the elements in the array are the values ​​of the original array elements after calling the function. The map() method processes elements sequentially in the original array element order.

 语法:
array.map(function(currentValue,index,arr), thisValue)
Copy after login

Note:

  • map() will not detect empty arrays.

  • map() does not change the original array.

This guy has done a lot of things he wants to do. The above is an example of state in React. Anyway, it will be used frequently. According to a certain condition, each element in the array executes the relevant function, which is pretty much what it means. The examples on the Internet all output an array, and each element is twice the original. Change it to a new one. If it is an odd number, it will output #, and if it is an even number, it will output *.

        var num = [1, 2, 3, 4, 5];        
        var newNum = num.map((item) => {            
        if(item%2) {                
        return '#';
            } else {                
            return '*';
            }
        });        console.log(newNum);
Copy after login

Iteration usage of Array in JavaScript

As for the usage of the optional parameter thisValue, it is similar to the above example, so I won’t write it again. Among the five, this one is the most practical and appears the most.

3.filter()

This is also a more useful method, used when filtering an array.

Definition: The filter() method creates a new array. The elements in the new array are checked for all elements in the specified array that meet the conditions.

 语法:
array.filter(function(currentValue,index,arr), thisValue)
Copy after login

Note:

  • filter() will not detect empty arrays.

  • filter() does not change the original array.

举个比较复杂的例子,在Todo的例子,很多框架都会用这个例子来展示自己这个框架的好处。Todo应用里有很多事项,有完成的,也未完成的,那么把完成的或未完成的筛选出来就需要用到这个了。

        var todos = [
            {name: 'todo1', completed: false}, 
            {name: 'todo2', completed: true},
            {name: 'todo3', completed: false}
        ];        var todosCompleted = todos.filter((todo) => {            
        return todo.completed;
        });        console.log(todosCompleted);
Copy after login

Iteration usage of Array in JavaScript

直截了当,比在for循环里写if判断简洁多了。

4.every()和some()

最后两个一起说,这两是兄弟,大的叫且(&&),小的叫或(||),给出定义也能看明白:

定义: every() 方法用于检测数组所有元素是否都符

合指定条件(通过函数提供)。every() 方法使用指定函数检测数组中的所有元素:
- 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测
- 如果所有元素都满足条件,则返回 true。

定义:some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。some() 方法会依次执行数组的每个元素:
- 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
- 如果没有满足条件的元素,则返回false。

注意的点:

  • 都不会对空数组进行检测。

  • 不会改变原始数组。

很少在项目中会想到这两兄弟,用for循环加上if判断,break退出循环就可以实现。用迭代方法就是要少写几行代码,js有一个库underscore,那更简洁。Backbone框架就依赖了这个库来实现对model和collection的便捷操作。最后一个例子结束这一讲,判断数组里的数字是否都是奇数(every),是否有偶数(some)。

        var num = [1, 3, 5, 6];        
        console.log(num.every((value) => {    // flase            
        return value%2;
        }));        
        console.log(num.some((value) => {     // true
            return !(value%2);
        }));
Copy after login

这两个方法比较聪明,对于every()方法,只要有一个结果是false,就直接返回false,后面的就不检测了。同理对于some()方法,只有出现返回true的结果,也就直接返回true,后面就不检测了。这个就不具体测试了,这样做就是为了提高效率,就是一个break的事。

总结

讲了五种Array的迭代方法,就是程序员偷懒搞的,还有更懒的方法,ES6里面的语法就更像天书了,比如箭头函数(=>)就是为了省写function这个单词,还有一个很牛逼的扩展操作符…,直接看呆。以后有机会慢慢来写这些看不懂的符号,这一次讲的迭代是后面的基础,常用的也就是forEach和map方法,多用就记住了。

The above is the detailed content of Iteration usage of Array in JavaScript. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!