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

How to operate Docker and images

Find mirror We can search for images from the Doc...

Graphic tutorial on configuring log server in Linux

Preface This article mainly introduces the releva...

SQL IDENTITY_INSERT case study

Generally speaking, once a column in a data table...

Complete steps to build a squid proxy server in linux

Preface This article mainly introduces the releva...

Docker container accesses the host's MySQL operation

background: There is a flask project that provide...

Detailed steps for smooth transition from MySQL to MariaDB

1. Introduction to MariaDB and MySQL 1. Introduct...

CSS3 achieves flippable hover effect

CSS3 implements a flippable hover effect. The spe...

Implementation of select multiple data loading optimization in Element

Table of contents Scenario Code Implementation Su...

MySQL permissions and database design case study

Permissions and database design User Management U...

MySQL backup table operation based on Java

The core is mysqldump and Runtime The operation i...

In-depth understanding of Vue's plug-in mechanism and installation details

Preface: When we use Vue, we often use and write ...

In-depth explanation of MySQL isolation level and locking mechanism

Table of contents Brief description: 1. Four char...

Linux hardware configuration command example

Hardware View Commands system # uname -a # View k...

js to implement verification code interference (static)

This article shares the specific code of js to im...