js高阶函数之filter、map、reduce
1. filter
filter中的回调函数需要返回一个boolean值。若返回true,则本次回调的元素,加入到新数组中;若返回false,则过滤掉本次回调的元素,不会加入到新数组中。
数组2 = this.数组1.filter(function (i) {
return true/false;
})
2. map
map:对数组中的所有元素都进行操作时使用。
数组2 = this.数组1.map(function (i) {
return xxx;
})
3. reduce
reduce:对数组中所有元素进行汇总。
//i为数组1中的元素(从第一个元素开始遍历),pre为i的前一个元素(默认第一次pre为0)
数组2 = this.数组1.reduce(function (pre, i) {
return xxx;
},y)
filter+map+reduce
简化
<!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>