Vue's js higher-order function 07

Filter, map, reduce of js higher-order functions

1. filter

The callback function in the filter needs to return a boolean value. If it returns true, the elements of this callback will be added to the new array; if it returns false, the elements of this callback will be filtered out and will not be added to the new array.

数组2 = this.数组1.filter(function (i) {
    
    
          return true/false;
        })

Insert picture description here

2. map

map: Used when operating on all elements in the array.

数组2 = this.数组1.map(function (i) {
    
    
          return xxx;
        })

Insert picture description here

3. reduce

reduce: Summarize all elements in the array.

//i为数组1中的元素(从第一个元素开始遍历),pre为i的前一个元素(默认第一次pre为0)
数组2 = this.数组1.reduce(function (pre, i) {
    
    
          return xxx;
        },y)

Insert picture description here

filter+map+reduce
Insert picture description here
Insert picture description here
simplified
Insert picture description here

Insert picture description here

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3js高阶函数</title>
</head>
<body>
  <div id="info">
    <h3>数组num={
   
   {num}}</h3>
    <h3>
      filter高阶函数:去除num中小于100的数存到newNum1中
      <button @click="getNewNum1">getNewNum1</button>
    </h3>
    <h3>newNum1 = {
   
   {newNum1}}</h3>

    <h3>
      map高阶函数:将newNum1的元素乘以2之后存到newNum2中
      <button @click="getNewNum2">getNewNum2</button>
    </h3>
    <h3>newNum2 = {
   
   {newNum2}}</h3>

    <h3>redece高阶函数:计算newNum2的总和</h3>
    <h3>newNum2Total = {
   
   {newNum2Total}}</h3>
    <h3>简化得:最总结果为:{
   
   {getLastNum}}</h3>
  </div>

  <script src="../../js/vue.js"></script>
  <script>
    const info = new Vue({
     
     
      el : "#info",
      data : {
     
     
        num: [444, 21, 54, 301, 14, 440, 97, 169, 42, 98],
        newNum1: [],
        newNum2: [],
      },
      methods : {
     
     
        getNewNum1(){
     
     
          this.newNum1 = this.num.filter(function (i) {
     
     
            return i < 100;
          })
        },
        getNewNum2(){
     
     
          this.newNum2 = this.newNum1.map(function (i) {
     
     
            return i * 2;
          })
        },
      },
      computed: {
     
     
        newNum2Total(){
     
     
          return this.newNum2.reduce(function (pre, i) {
     
     
            console.log(pre)
            return pre + i;
          },0)
        },
        
        getLastNum(){
     
     
          return this.num.filter(function (i){
     
     
            return i < 100;
          }).map(function (i) {
     
     
            return i * 2;
          }).reduce(function (pre, i) {
     
     
            return pre + i;
          },0)
        }
      }

    })
  </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_44836362/article/details/114672296