一. 常用的數(shù)組的高階函數(shù)
假設(shè), 現(xiàn)在有一個數(shù)組, 我們要對數(shù)組做如下一些列操作
1. 找出小于100的數(shù)字:
2. 將小于100的數(shù)字, 全部乘以2:
3. 在2的基礎(chǔ)上, 對所有數(shù)求和:
通常我們會怎么做呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<p>找出小于100的數(shù)字:</p>
<p>將小于100的數(shù)字, 全部乘以2: </p>
<p>對所有數(shù)求和:</p>
<button @click="getNum()">計算</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. 找出<100的數(shù)字
let newNum1 = []
for(let num of this.nums) {
if (num < 100) {
newNum1.push(num)
}
}
this.num1=newNum1
console.log(newNum1)
// 2. 對小于100的數(shù)字*2
let newNum2 = []
for(let num of newNum1) {
newNum2.push(num * 2)
}
this.num2 = newNum2
console.log(newNum2)
// 3. 對小于100的數(shù)字*2后求和
let newNum3 = 0;
for(let num of newNum2) {
newNum3 += num
}
this.num3 = newNum3
console.log(newNum3)
}
}
})
</script>
</body>
</html>
在上面的demo中, 我們?nèi)慷际鞘褂醚h(huán)來進行計算, 并且最后達到了我們想要的效果. 點擊計算按鈕, 查看計算結(jié)果:
在js高階函數(shù)里面, 有一些高階函數(shù)是可以直接計算得到上面的效果的. 下面主要介紹三個高階函數(shù)
- filter
- map
- **reduce **
1. filter函數(shù)
filter()方法會創(chuàng)建一個新數(shù)組磨德,原數(shù)組的
每個元素傳入回調(diào)函數(shù)中,回調(diào)函數(shù)中有return返回值,若返回值為true辣之,這個元素保存到新數(shù)組中凉袱;若返回值為false舟扎,則該元素不保存到新數(shù)組中梯澜;原數(shù)組不發(fā)生改變喇潘。
- 語法: array.filter(function(currentValue,index,arr), thisValue)
- 參數(shù)
舉例1: 返回數(shù)組中<100的元素
getNums() {
// 來看看filter的用法
let num1 = [10 ,20, 100, 30, 320, 55. 80, 210]
let newNum1 = this.nums.filter(function (num) {
return num < 100;
})
console.log(newNum1)
}
- filter()函數(shù)的入?yún)⑹且粋€function, 出參是一個新的數(shù)組
- function函數(shù)也有參, 這里只傳入了第一個入?yún)? 表示: 循環(huán)遍歷時的數(shù)組元素.
- function的返回值類型是true或false, 如果返回結(jié)果是true, 則返回新數(shù)組中有這個元素, 返回結(jié)果是false, 則返回新數(shù)組中沒有這個元素
舉例2: 利用filter
肮雨,可以巧妙地去除Array
的重復(fù)元素:
filter()
接收的回調(diào)函數(shù)遵堵,其實可以有多個參數(shù)。通常我們僅使用第一個參數(shù)怨规,表示Array
的某個元素陌宿。回調(diào)函數(shù)還可以接收另外兩個參數(shù)波丰,表示元素的位置和數(shù)組本身:
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
})
運行結(jié)果
[10, 20, 100, 30, 320, 55, 80, 210]
去除重復(fù)元素依靠的是indexOf
總是返回第一個元素的位置壳坪,后續(xù)的重復(fù)元素位置與indexOf
返回的位置不相等,因此被filter
濾掉了呀舔。
2. map函數(shù)
方法返回一個新數(shù)組弥虐,新數(shù)組中的每一個元素為原始數(shù)組對應(yīng)每一個元素調(diào)用函數(shù)處理后的值;不會對空數(shù)組進行編輯媚赖,不改變原來的數(shù)組霜瘪。
- 語法: array.every(function(item,index,array){})
- 參數(shù):
舉例1: 求數(shù)組中所有元素*2后的數(shù)組
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)
輸出結(jié)果:
[20, 40, 200, 60, 640, 110, 160, 420, 40, 110, 640]
3. reduce函數(shù)
reduce() 方法接收一個函數(shù)作為累加器
,reduce 為數(shù)組中的每一個元素依次執(zhí)行回調(diào)函數(shù),數(shù)組中被刪除或從未被賦值的元素不處理.
- 語法: arr.reduce(callback,[initialValue])
- 參數(shù)
案例1: 求一個數(shù)組的和
// 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)
二. 綜合案例1
結(jié)合filter, map, reduce三個函數(shù), 獲取數(shù)組中<100的元素, 然后對這些元素同意5, 最后求5后的所有元素的和**
// 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)
輸出結(jié)果: 1220
其實還有更簡單的算法, lambda表達式
// 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)
執(zhí)行結(jié)果: 150
三.綜合案例2
顯示一個列表, 選中那個那個變色, 使用vue實現(xiàn)
可以思考兩分鐘, 看看, 如何來設(shè)計.
在vue中, 這個過程將非常簡單
- 第一步: 定義了一個isCurrentIndex用來記錄當(dāng)前選中元素的下標(biāo).
- 第二步: 在class屬性中設(shè)置 :isCurrentIndex == index. 表示選中元素的下標(biāo)顯示紅色, 其他不顯示紅色.
- 第三步: 定義一個click事件, 每次點擊事件, 修改選中的下標(biāo)值
代碼如下所示:
<!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語言"],
isCurrentIndex:0
},
methods: {
changeCurrentIndex(index) {
this.isCurrentIndex = index
}
}
});
</script>
</body>
</html>
四. 綜合案例3
我們要做一個表格, 具體內(nèi)容如下
** 主要有哪些東西呢?**
- 有n本書, 書有書名, 出版日期, 價格, 數(shù)量, 操作
- 價格保留兩位小數(shù), 數(shù)量可增減, 最多減到0,
- 操作可以刪除表格 ,當(dāng)表格沒有數(shù)據(jù)時顯示無數(shù)據(jù)
- 隨時計算總價格.
下面來看看這個代碼如何實現(xiàn), 結(jié)合我們之前學(xué)過的js高階函數(shù)
第一步: 定義了n本書, 放在vue的data屬性里面
data: {
books: [
{name:"java設(shè)計模式", publishDate:"1998-10-21", price: 58.00, count: 1},
{name:"go語言實戰(zhàn)分析", publishDate:"2018-5-12", price: 70.00, count: 1},
{name:"vue深入淺出", publishDate:"2019-08-09", price: 46.89, count: 1},
{name:"jquery實戰(zhàn)", publishDate:"2014-02-29", price: 39.98, count: 1}
],
total: 0
},
定義了一個總價格, 用來保存計算后的總價格
第二步: 畫table
<div id="app">
<table border="1">
<thead>
<tr>
<td>序號</td>
<td>書名</td>
<td>出版日期</td>
<td>價格</td>
<td>購買數(shù)量</td>
<td>操作</td>
</tr>
</thead>
<tbody v-if="books.length==0">
<tr>
<td colspan="6" >沒有數(shù)據(jù)</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)">刪除</button>
</tr>
</tbody>
</table>
<label id="sum">總價: {{getTotal() | priceUnit}} </label>
</div>
在這里我們循環(huán)遍歷了data數(shù)據(jù), 然后對價格進行了處理, 增加了單位, 對數(shù)量增加了增減的button. 最后定義了一個刪除功能
第三步. 使用過濾器格式化價格
在對價格進行格式化的時候, 使用了管道符.這是過濾器的寫法. 不加過濾器之前, 價格是58. 加了過濾器之后是: $58.00, 增加了一個美元符號, 價格保留兩位小數(shù)
因為不止有一個地方會用到加單位, 所以, 我們將其定義為一個方法. 如下寫法
filters: {
priceUnit(price) {
return "$" + price.toFixed(2)
}
}
這里定義了過濾器的寫法. 類似于methods. 里面定義一個方法. 其實這個方法可不可以放在methods中呢? 也可以, 但是放在filters有一個好處. 可以使用管道符寫法
<td>{{item.price | priceUnit}} </td>
使用過濾器, 會自動將 | 前面的值作為參數(shù)傳遞給priceUnit
第四步: 定義methods, 對圖書數(shù)量進行增減, 且做少不能少于0
sub(index) {
if (this.books[index].count <= 0) {
this.books[index].coun = 0;
} else {
this.books[index].count --;
}
},
add(index) {
this.books[index].count ++;
},
這個就不多說了, 普通函數(shù)寫法
第五步: 計算總額
計算總額有多種寫法, 常規(guī)寫法
getTotal() {
let totalPrice = 0;
for(let i = 0; i < this.books.length; i++) {
totalPrice += this.books[i].price * this.books[i].count;
}
return totalPrice;
},
循環(huán)遍歷books, 價格和數(shù)量乘積的和
推薦使用js的高階函數(shù)
getTotal() {
// 使用數(shù)組的高階函數(shù)計算每種書的價格總和
return this.books.map((book)=>book.price * book.count).reduce((total,num) => total + num)
},
在回顧一下
- map是對數(shù)組的每一個元素執(zhí)行操作
- reduce是對數(shù)組中所有元素求和
第六步: 刪除表格行
del(index){
this.books.splice(index,1)
}
刪除行, 使用splice刪除指定的data中的元素, 就可以了
作者:盛開的太陽
原文鏈接:https://www.cnblogs.com/ITPower/p/14433937.html