vue中三種for循環與高階函數(filter、map、reduce)的使用


for循環的三種用法

1、第一種是我們平常用的最多的for循壞 如: 普通的for循環 ,顯得繁瑣,i為for為數組賦予的序號

let totalPrice = 0
  for (let i = 0; i < this.books.length; i++) {
    totalPrice += this.books[i].price * this.books[i].count
}

2、第二種for in 循壞,in對應的是數組對象名字,i 也是數組的序號

let totalPrice = 0
  for (let i in this.books) {
    const book = this.books[i]
    totalPrice += book.price * book.count
}

3、第三種,item代表的是數組里具體的其中一個元素

let totalPrice = 0
  for (let item of this.books) {
  totalPrice += item.price * item.count
}

顯然第三種for 更直接有簡便,下面用這第三種for循環來實現對數組進行判斷,改變和匯總操作

1、需求: 取出所有小於100的數字

let newNums = []
  for (let n of nums) {
    if (n < 100) {
      newNums.push(n)
   }
}

2、需求:將所有小於100的數字進行轉化: 全部*2

let new2Nums = []
  for (let n of newNums) {
    new2Nums.push(n * 2)
}
console.log(new2Nums);

3、需求:將所有new2Nums數字相加,得到最終的記過

let total = 0
  for (let n of new2Nums) {
    total += n
}
console.log(total);

上面的操作雖然實現了這三種需求,但是還是太繁瑣,使用高階函數(filter、map、reduce)可以更便捷的實現需求
第一種是filter的使用:參數是回調函數
filter中的回調函數有一個要求: 必須返回一個boolean值
true: 當返回true時, 函數內部會自動將這次回調的n加入到新的數組中
false: 當返回false時, 函數內部會過濾掉這次的n

const nums = [10, 20, 111, 222, 444, 40, 50]
 let newNums = nums.filter(function (n) {
  return n < 100  //這里返回了 10 20 40 50
 })
console.log(newNums);

第二種是map函數的使用:對數組進行遍歷了一遍,並且return 回數組 參數也是回調函數

// 20, 40, 80, 100
let new2Nums = newNums.map(function (n) { // 20
  return n * 2
})

第三種是reduce函數的使用 ,參數有兩個,還分別是回調函數 和 preValue 的初始值
reduce作用對數組中所有的內容進行匯總

let total = new2Nums.reduce(function (preValue, n) {
  return preValue + n   //這個preValue就代表上一個值,比如當 preValue 0 ,n 為20 時候 返回20
                        //后面當  preValue就等於 20 ,那么 n 自然就為40  結果是60
}, 0)    
console.log(total);
//第一次: preValue 0 n 20
//第二次: preValue 20 n 40
//第二次: preValue 60 n 80
//第二次: preValue 140 n 100
//total:240

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM