1. Commonly used high-order functions of arraysSuppose, now there is an array, and we want to perform the following operations on the array
What do we usually do? <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <p>Find a number less than 100:</p> <p>Multiply all numbers less than 100 by 2: </p> <p>Sum all numbers:</p> <button @click="getNum()">Calculate</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: "#app", data: { nums: [10, 20, 100, 30, 320, 55, 80, 210], num1:0, num2:0, num3:0 }, methods: { getNum(){ // 1. Find a number < 100 let newNum1 = [] for(let num of this.nums) { if (num < 100) { newNum1.push(num) } } this.num1=newNum1 console.log(newNum1) // 2. For numbers less than 100 * 2 let newNum2 = [] for(let num of newNum1) { newNum2.push(num * 2) } this.num2 = newNum2 console.log(newNum2) // 3. Sum the numbers less than 100 * 2 let newNum3 = 0; for(let num of newNum2) { newNum3 += num } this.num3 = newNum3 console.log(newNum3) } } }) </script> </body> </html> In the above demo, we all use loops to perform calculations, and finally achieve the desired effect. Click the calculation button to view the calculation results: In js high-order functions, some high-order functions can directly calculate the above effects. The following mainly introduces three high-order functions
1. Filter functionThe filter() method creates a new array. Each element of the original array is passed to the callback function. The callback function has a return value. If the return value is true, the element is saved in the new array. If the return value is false, the element is not saved in the new array. The original array does not change.
Example 1: Return the elements in the array that are less than 100 getNums() { // Let's see how to use the filter let num1 = [10, 20, 100, 30, 320, 55. 80, 210] let newNum1 = this.nums.filter(function (num) { return num < 100; }) console.log(newNum1) }
Example 2: Using filter, you can cleverly remove duplicate elements from an Array: The callback function received by filter() can actually have multiple parameters. Usually we only use the first parameter, which represents an element of the Array. The callback function can also receive two additional parameters, indicating the position of the element and the array itself: let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320] let newNum2 = this.nums.filter(function(element, index, self) { return self.indexOf(element) == index }) Operation Results
Removing duplicate elements relies on the fact that indexOf always returns the position of the first element. The positions of subsequent duplicate elements are not equal to the position returned by indexOf, so they are filtered out by the filter. 2. Map FunctionThe method returns a new array, each element of which is the value of the original array after calling the function on each element; the empty array will not be edited and the original array will not be changed.
Example 1: Find the array after all elements in the array are multiplied by 2 let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320] let newNum1 = this.nums.map(function (num) { return num * 2; }) console.log(newNum1) Output:
3. Reduce functionThe reduce() method receives a function as an accumulator. Reduce executes the callback function for each element in the array in turn. Elements in the array that have been deleted or never assigned a value are not processed.
Example 1: Find the sum of an array // usage of reduce let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320] let newNum1 = this.nums.reduce(function (total, num) { return num + total; }, 0) console.log(newNum1) 2. Comprehensive Case 1Combine the three functions of filter, map, and reduce to get the elements in the array that are less than 100, then multiply these elements by *5, and finally find the sum of all the elements after *5. // usage of reduce let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320] let newNum1 = this.nums.filter(function (number) { return number < 100 }).map(function (number) { return number * 5 }).reduce(function (total, num) { return num + total; }, 0) console.log(newNum1)
In fact, there is a simpler algorithm, lambda expression // Usage of reduce let nums = [10, 20, 320] let newNum11 = nums.filter(num => num < 100).map(num => num * 5, this).reduce((total, num) => total + num) console.log(newNum11)
3. Comprehensive Case 2Display a list, select the one that changes color, use vue to implement Think about it for two minutes and see how to design it. In Vue, this process will be very simple
The code is as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .action { color: red; } </style> </head> <body> <div id="app"> <ul> <li v-for="(item, index) in languages" :class="{action:isCurrentIndex == index}" @click="changeCurrentIndex(index)"> {{index}}--{{item}}</li> </ul> </div> <script src="../js/vue.js"></script> <script> var app = new Vue({ el: "#app", data: { languages: ["java", "php", "python", "go", "c language"], isCurrentIndex:0 }, methods: { changeCurrentIndex(index) { this.isCurrentIndex = index } } }); </script> </body> </html> IV. Comprehensive Case 3We need to make a table with the following contents: What are the main things?
Let's take a look at how this code is implemented, combined with the js high-order functions we learned before Step 1: Define n books and put them in the data attribute of vuedata: { books: {name:"java design pattern", publishDate:"1998-10-21", price: 58.00, count: 1}, {name:"Go Language Practical Analysis", publishDate:"2018-5-12", price: 70.00, count: 1}, {name:"vue is easy to understand", publishDate:"2019-08-09", price: 46.89, count: 1}, {name:"jquery in action", publishDate:"2014-02-29", price: 39.98, count: 1} ], total: 0 }, Defines a total price to save the calculated total price Step 2: Draw the table<div id="app"> <table border="1"> <thead> <tr> <td>Serial number</td> <td>Book Title</td> <td>Publication Date</td> <td>Price</td> <td>Purchase quantity</td> <td>Operation</td> </tr> </thead> <tbody v-if="books.length==0"> <tr> <td colspan="6" >No data</td> </tr> </tbody> <tbody v-else> <tr v-for="(item, index) in books" > <td>{{index+1}}</td> <td>{{item.name}}</td> <td>{{item.publishDate}}</td> <td>{{item.price| priceUnit}} </td> <td> <button @click="sub(index)">-</button> {{item.count}} <button @click="add(index)">+</button> </td> <td> <button @click="del(index)">Delete</button> </tr> </tbody> </table> <label id="sum">Total price: {{getTotal() | priceUnit}} </label> </div> Here we loop through the data, process the price, add units, and add buttons to increase and decrease the quantity. Finally, we define a delete function. Step 3. Format the price using filtersWhen formatting the price, the pipe character is used. This is how the filter is written. Before the filter, the price is 58. After the filter is added, it is: $58.00, with a dollar sign added and the price is rounded to two decimal places. Because adding units is used in more than one place, we define it as a method. filters: priceUnit(price) { return "$" + price.toFixed(2) } } Here is the definition of how to write a filter. It is similar to methods. A method is defined in it. In fact, can this method be placed in methods? Yes, but there is an advantage of putting it in filters. You can use the pipe character to write it. <td>{{item.price | priceUnit}} </td> Using the filter, the value before | will be automatically passed as a parameter to priceUnit Step 4: Define methods to increase or decrease the number of books, and the number cannot be less than 0sub(index) { if (this.books[index].count <= 0) { this.books[index].count = 0; } else { this.books[index].count --; } }, add(index) { this.books[index].count++; }, I won't say much about this, ordinary function writing Step 5: Calculate the total amountThere are many ways to calculate the total amount. The conventional way is getTotal() { let totalPrice = 0; for(let i = 0; i < this.books.length; i++) { totalPrice += this.books[i].price * this.books[i].count; } return totalPrice; }, Loop through books, sum of price and quantity multiplied by It is recommended to use js's high-order functions getTotal() { // Use higher-order functions on arrays to calculate the total price of each book return this.books.map((book)=>book.price * book.count).reduce((total,num) => total + num) }, In review Map performs an operation on each element of an array. Reduce is to sum all the elements in the array Step 6: Delete table rowsdel(index){ this.books.splice(index,1) } To delete a row, use splice to delete the elements in the specified data. This is the end of this article about Vue's commonly used high-order functions and comprehensive cases. For more relevant Vue's commonly used high-order functions and examples, 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 construction and use of docker private warehouse
>>: Commonplace talk about MySQL event scheduler (must read)
Table of contents Implementation ideas: Step 1: C...
1. Basic steps 1: Install yarn add vue-i18n Creat...
How to use if in Linux to determine whether a dir...
Table of contents 1. Location Object 1. URL 2. Pr...
1. Flex layout .father { display: flex; justify-c...
1. CSS3 animation ☺CSS3 animations are much easie...
MySQL and connection related timeouts Preface: To...
Introduction The meta tag is an auxiliary tag in ...
Table of contents 1. Custom import in packaging t...
The optimization created by MySQL is to add index...
This article example shares the specific code for...
Table of contents What is native JavaScript A. Ch...
Table of contents Preface text 1. Panel 2. Huaron...
Downloaded the unzipped version of mysql-5.6.37-w...
1|0MySQL (MariaDB) 1|11. Description MariaDB data...