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

Linux file management command example analysis [display, view, statistics, etc.]

This article describes the Linux file management ...

How to implement Linux deepin to delete redundant kernels

The previous article wrote about how to manually ...

When you enter a URL, what exactly happens in the background?

As a software developer, you must have a complete...

How to use the jquery editor plugin tinyMCE

Modify the simplified file size and download the ...

How to add Lua module to Nginx

Install lua wget http://luajit.org/download/LuaJI...

Implementation of MySQL scheduled database backup (full database backup)

Table of contents 1. MySQL data backup 1.1, mysql...

Detailed explanation of Vue lazyload picture lazy loading example

Documentation: https://github.com/hilongjw/vue-la...

A Deep Dive into JavaScript Promises

Table of contents 1. What is Promise? 2. Why is t...

MySQL data type optimization principles

MySQL supports many data types, and choosing the ...

Detailed process of FastAPI deployment on Docker

Docker Learning https://www.cnblogs.com/poloyy/p/...

Use pictures to realize personalized underline of hyperlinks

Don't be surprised if you see some kind of und...