Vue must learn knowledge points: the use of forEach()

Vue must learn knowledge points: the use of forEach()

Preface

In front-end development, we often encounter situations where we need to traverse loops to get the desired content, and this situation is ubiquitous in development. This blog post will share a more common and classic knowledge point: the use of forEach().

forEach() is a method for operating arrays in front-end development. Its main function is to traverse the array. In fact, it is an upgraded version of the for loop. This statement requires a callback function as a parameter. The parameters of the callback function are: 1. value: traverse the contents of the array; 2. index: the index of the corresponding array; 3. array: the array itself.

In Vue projects, v-for is used for loops in tags, and forEach is used for loops in methods.

1. Principle of forEach()

The forEach() method is mainly used to call each element of an array and pass the element to a callback function. It should be noted that the forEach() method will not execute the callback function for an empty array.

forEach: Array.prototype.forEach, a method that only exists in arrays, equivalent to a for loop that traverses the array. Usage: arr.forEach(function(item,index,array){...}), where the callback function has 3 parameters, item is the element currently traversed, index is the index of the element currently traversed, and array is the array itself. The forEach method does not skip null and undefined elements. For example, all four elements in the array [1, undefine, null, , 2] will be traversed. Note the difference from map.

2. forEach() Syntax

array.forEach(function(currentValue, index, array), thisValue)

example:

array.forEach(function(item,index,array){ ... })

3. forEach() Other related content

1. forEach()'s continue and break:

forEach() itself does not support continue and break statements, but can be implemented through some and every.

2. The difference between forEach() and map:

forEach() has no return value and is essentially the same as a for loop, executing the function for each item. That is, map returns a new array, leaving the original array unchanged, while forEach changes the original array.

3. Comparison between forEach() and for loop:

The for loop has many steps and is relatively complicated, while the forEach loop is relatively simple, easy to use and less prone to errors.

4. forEach() Example:

Example 1:

let array = [1, 2, 3, 4, 5, 6, 7];
array.forEach(function (item, index) {
    console.log(item); //output each element of the array});

Example 2:

var array = [1, 2, 3, 4, 5];
array.forEach(function(item, index, array){
    array[index]=4 * item;
});
console.log(array); //Output result: The original array elements are modified, and each element is multiplied by 4

Example 3:

 <el-checkbox v-for="(item) in searchContent"
                       :label="item.id"
                       :key="item.id"
                       class="checkbox">
            <span>{{item.value}}{{item.checked}}</span>
          </el-checkbox>
  handle(index, row) {
        this.selectedCheck=[];
        let a = this;
        this.jurisdiction = true;
        this.roleId = row.id;
        this.$http.get("/user/resources", {
            params: {userId: this.userId}
          }).then((response) => {
          a.searchContent = response.body;
          a.searchContent.forEach(function (b) {
            if(b['checked']){
              a.selectedCheck.push(b.id);
            }
          })
        })

Example 4:

var userList = new Array();
        var data = {};
        if (response.data.userList != null && response.data.userList.length > 0) {
          response.data.userList.forEach((item, index) => {

            data.a = item.a;
            data.b = item.b;
            data.arr1 = new Array();
            data.arr1[0] = item.c;
            data.arr1[1] = item.d;
            data.e = item.e;
            data.f = item.f;
            data.arr2 = new Array();
            data.arr2[0] = item.j;
            data.arr2[1] = item.h;
            userList.push(data);
          });
        }

Example 5:

searchDept(keyWord, callback) {
       if (keyWord) {
        this.$service.data
          .searchDepts({ data: { full_name: keyWord } })
          .then(r => {
            if (r.Success) {
              let arr = [];
              r.Data.Result.forEach(element => {
                arr.push({
                  id: element.work_id,
                  value: element.full_name,
                  dept: element
                });
              });
              callback(arr);
            }
         });
      }
    },

Summarize

This is the end of this article about the use of forEach(), a must-learn knowledge point in Vue. For more relevant content on the use of Vue forEach(), please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the principle analysis and practical application of Vue array traversal methods forEach and map
  • Vue forEach loop array to get the data you want
  • Use vue-router beforEach to implement the function of judging user login jump route filtering
  • Vue.js double nested for traversal method detailed explanation, similar to php foreach()

<<:  Detailed analysis and testing of SSD performance issues in MySQL servers

>>:  How to install Django in a virtual environment under Ubuntu

Recommend

MySQL Billions of Data Import, Export and Migration Notes

I have been taking a lot of MySQL notes recently,...

MySQL Order By Multi-Field Sorting Rules Code Example

Say it in advance On a whim, I want to know what ...

How to use Font Awesome 5 in Vue development projects

Table of contents Install Dependencies Configurat...

Detailed explanation of MySQL batch SQL insert performance optimization

For some systems with large amounts of data, the ...

How to view and close background running programs in Linux

1. Run the .sh file You can run it directly using...

MySQL's conceptual understanding of various locks

Optimistic Locking Optimistic locking is mostly i...

Monitor changes in MySQL table content and enable MySQL binlog

Preface binlog is a binary log file, which record...

How to use Docker Swarm to build WordPress

cause I once set up WordPress on Vultr, but for w...

Example of Vue transition to achieve like animation effect

Table of contents Results at a Glance Heart Effec...

How to express relative paths in Linux

For example, if your current path is /var/log and...

5 ways to achieve the diagonal header effect in the table

Everyone must be familiar with table. We often en...

CSS3 mobile vw+rem method to achieve responsive layout without relying on JS

1. Introduction (1) Introduction to vw/vh Before ...

JavaScript implementation of drop-down list

This article example shares the specific code of ...