A brief discussion on the built-in traversal methods of JS arrays and their differences

A brief discussion on the built-in traversal methods of JS arrays and their differences

forEach() (ES6) method

The forEach() (ES6) method executes a given function once for each element of an array.

1. The callback in this method will be executed as many times as the number of elements in the array
2. The first parameter is the element in the array, the second parameter is the index of the element in the array, and the third parameter is itself (the third parameter can be used to deduplicate the array)
3. The array's own traversal method, foreach, is more efficient than the for loop when the number of loops is unknown or the calculation is complex.
4. The looped array elements are basic data types, which will not change the data of the original data. The looped array elements are objects, which will change the values ​​of the object attributes of the original array.
5. Index modification is not supported during the loop. Using return in the callback will not report an error, but it is invalid.

Note: You cannot use break and continue to jump out of the entire loop or the current loop, an error will be reported, but you can jump out of the loop by combining try...catch

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

Disadvantage: No way to abort or jump out of a `forEach()` loop

map() (ES6) method

The map() (ES6) method creates a new array where each element is the return value of calling the provided function once.

    const array1 = [1, 4, 9, 16];
    const map1 = array1.map(x => x * 2);
    console.log(map1); //[2, 8, 18, 32]

Three parameters: array element, element index, and the original array itself

flatMap() Method

The flatMap() method first maps each element using the mapping function and then zips the results into a new array. It is almost the same as map followed by flat with a depth of 1, but flatMap is usually slightly more efficient when combined into one method.

    var arr1 = [1, 2, [3, 4]];
    arr1.flatMap(x => x); //[1, 2, 3, 4]
    var arr1 = [1, 2, 3, 4];
    arr1.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]

for...in...

This loop is also used by many people, but it is the least efficient (the output key is the array index). If the object is traversed, the output is the attribute name of the object.

for...of...

The performance is better than `for..in...`, but still not as good as a normal `for` loop
Note: Objects cannot be looped, because any data structure can be traversed as long as the Iterator interface is deployed. Some data structures have the Iterator interface natively, such as Array, Map, Set, String, etc., and the Iterator interface is deployed on the Symbol.iterator attribute of the data structure, but the object Object does not have the Symbol.iterator attribute, so it cannot be traversed by for..of

filter (ES6) traverses the array

filter (ES6) traverses the array, filters out the elements that meet the conditions and returns a new array. If no array elements pass the test, an empty array is returned.

    const result = words.filter(word => word.length > 6);
    console.log(result) //["exuberant", "destruction", "present"]
some() function (ES6)
    Iterates through the array to see if there are elements that meet the conditions. The return value is a Boolean value. As long as it finds one that meets the conditions, it returns true.
    var arr = [
     { id: 1, name: 'Buy a pen', done: true },
     { id: 2, name: 'Buy a laptop', done: true },
     { id: 3, name: 'Practice calligraphy', done: false }
    ]
    
    var bool = arr.some(function (item, index) {
     return item.done
    })
    console.log(bool) // true

every() function (ES6)

Tests whether each element of the array passes the test of the callback function
If all pass, return true, otherwise return false
Simply put, if the callback function returns true each time, then every() returns true, otherwise false.

    var arr = [
        { id: 1, name: 'Buy a pen', done: true },
        { id: 2, name: 'Buy a laptop', done: true },
        { id: 3, name: 'Practice calligraphy', done: false }
    ]
    var bool = arr.every((item, index) => {
        return item.done
    })
    console.log(bool) // false

find() function (ES6)

Returns the first element that passes the test. If no element passes the test, it returns **undefined**.

    var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
    var num = arr.find( (item, index) => {
        return item === 3
    })
    console.log(num) // 3

findIndex() Function (ES6)

This function has the same effect as find() above, except that it returns the index of the first element passed.

    var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
    var num = arr.findIndex(item => {
        return item === 3
    })
    console.log(num) // 4

This concludes this article on the built-in traversal methods of JS arrays and their differences. For more relevant content on built-in traversal of JS arrays, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of several common methods of JavaScript arrays
  • Detailed explanation of the difference between javascript array traversal for and for in
  • Javascript array and dictionary usage and object attribute traversal skills
  • JS array and object traversal method code summary
  • JS array loop method and efficiency analysis comparison

<<:  WEB standard web page structure

>>:  Selection and thinking of MySQL data backup method

Recommend

How to get the current time using time(NULL) function and localtime() in Linux

time(); function Function prototype: time_t time(...

How to use bind to set up DNS server

DNS (Domain Name Server) is a server that convert...

Overview of MySQL Statistics

MySQL executes SQL through the process of SQL par...

JavaScript Regular Expressions Explained

Table of contents 1. Regular expression creation ...

How to use Portainer to build a visual interface for Docker

Portainer Introduction Portainer is a graphical m...

CSS implementation code for drawing triangles (border method)

1. Implement a simple triangle Using the border i...

Analysis of the problem of deploying vue project and configuring proxy in Nginx

1. Install and start nginx # Install nginx sudo a...

MySQL 8.0.3 RC is about to be released. Let’s take a look at the changes

MySQL 8.0.3 is about to be released. Let’s take a...

JavaScript implements circular progress bar effect

This article example shares the specific code of ...

404 error occurs when accessing the homepage of tomcat started in Docker mode

Scenario: When starting tomcat in docker (version...

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

Let's talk in depth about the principle and implementation of new in JS

Table of contents definition Constructor bodies a...

Detailed usage of Vue more filter widget

This article example shares the implementation me...

JavaScript to implement login slider verification

This article example shares the specific code of ...