<body>
<div id="app">
<ul>
<li v-for="item in list">{{item}}</li>
</ul>
<div v-for="item in line">{{item}}</div>
<button @click="btnClick">点击</button>
</div>
<script src="../js/vue.js"></script>
<script>
const vm = new Vue({
el: "#app",
data: {
list: ['aplle', 'pear', 'banana'],
line: [1, 44, 77, 3, 99],
},
methods: {
btnClick() {
//具有响应式的方法
//1.push()方法---在数组元素的后面添加元素
// this.list.push('lemo');
// this.list.push('lemo','apple');
//2。pop()方法---删除数组元素的最后一位
// this.list.pop();
//3.shift()方法---删除数组元素的第一位
// this.list.shift();
//4.unshift()方法---在数组的最前面添加元素
// this.list.unshift('a', 'b');
//5.splice()方法---用于删除、插入、替换元素
// 参数一:起始元素位置 参数二:要删除的元素个数 参数三:要添加的元素
//删除元素---起始位置,加上删除袁术那个数
//替换元素---先起始位置开始,删除两个元素,然后在添加两个元素,类似于替换
//插入元素---起始位置,删除元素的位置设置为0,
// this.list.splice(1, 1);//删除元素
// this.list.splice(1, 2, 'aaa', 'bbb');//替换元素
// this.list.splice(1, 0, 'aa', 'cc'); //插入元素
//6.sort()方法---排序方法
// this.line.sort(function (a, b) {
// return a - b; //升序
// })
//7.reverse()方法---数组的翻转
// this.list.reverse();
//0---通过下标来修改数组的值---无法做到响应式
// this.list[2] = 'orange';
//需要修改数组中一个值,可以通过splice方法来替换
// this.list.splice(0, 1, 'aaa'); //把数组的第一个值替换为aaa
//或者通过Vue.set(要修改的数组,数组的修改下标,修改后的值)
Vue.set(this.list, 0, 'aaa');
}
}
});
</script>
</body>
二、高阶函数
(1):filter()
//1:filter()中的回调函数会返回一个boolean值,
// 若为true的时候,函数内部会回调这个value假如到新的数组(需要定义个新数组接受)
//若为false的时候,函数会过滤掉value的值
回调函数的参数:value值,index,arr(原数组) 经常用到的是value
//需求1:过滤---小于100的数组
let arr = [10, 200, 40, 20, 777, 80, 100];
let newArr1 = arr.filter(function (value, index, arr) {
return value <= 100;
})
console.log(newArr1); //[10, 40, 20, 80, 100]
(2):map()
map() 方法返回一个新数组,新数组中的元素为原始数组元素调用函数处理后的值。
需求2:对newArr1的数组,每一个元素进行*2
let newArr2 = newArr1.map(function (value, index, arr) {
return value * 2;
});
console.log(newArr2); //[20, 80, 40, 160, 200]
(3):reduce()
//3:reduce()函数-对数组中所有的内容进行汇总 (求和)
//里面有两个参数 第一个参数为回调函数,第二个参数为初始化值(一般设置为0)
//回调函数内部的参数有—
//第一个参数–上一次的值 第二个参数—当前的值 第三个参数—当前的索引号 第四个值—
需求三:对newArr2数组中进行求和(汇总)
let total3 = newArr2.reduce(function (preValue, n) {
return preValue + n;
}, 0);
console.log(total3); //500
//第一次:preValue 0 n-20
//第二次:preValue 20 n-80
//第三次:preValue 100 n-40
//第四次:preValue 140 n-160
//第五次:preValue 300 n-200
(4):三个高阶函数的综合使用
let nums = [10, 20, 111, 222, 444, 40, 50];
需求1:求数组中小于等于100的数组
需求2:在需求一的基础下,对每一项数组元素*2
需求3:在需求而的基础下,对数组进行汇总
let nums = [10, 20, 111, 222, 444, 40, 50];
let total4 = nums.filter(function (n) {
return n < 100;
}).map(function (n) {
return n * 2;
}).reduce(function (preValue, n) {
return preValue + n;
});
console.log(total4); //240