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

Some problems that may be caused by inconsistent MySQL encoding

Stored procedures and coding In MySQL stored proc...

Detailed discussion of the differences between loops in JavaScript

Table of contents Preface Enumerable properties I...

Implementing a simple Gobang game with native JavaScript

This article shares the specific code for impleme...

Web Design Experience: Efficiently Writing Web Code

Originally, this seventh chapter should be a deep ...

Solution to forgetting the password of the pagoda panel in Linux 3.X/4.x/5.x

Enter ssh and enter the following command to rese...

jQuery implements simple pop-up window effect

This article shares the specific code of jQuery t...

Detailed explanation and examples of database account password encryption

Detailed explanation and examples of database acc...

Analysis of idea compiler vue indentation error problem scenario

Project scenario: When running the Vue project, t...

HTML sub tag and sup tag

Today I will introduce two HTML tags that I don’t...

How to upgrade https under Nginx

Purchase Certificate You can purchase it from Ali...

Native JS to achieve drag photo wall

This article shares with you a draggable photo wa...

Detailed tutorial on installing Docker on CentOS 8

1. Previous versions yum remove docker docker-cli...

Vue improves page response speed through lazy loading

Table of contents Overview What is lazy loading? ...