数组filter用于筛选数组,并且将满足条件的元素放入新数组中
语法 :let newArray = array.filter( function ( item, index,arr) {} )
参数:
- item:必须,当前元素的值
- index:可选,当前元素在数组中的索引值
- arr:可选,当前元素所处的数组对象
返回值: - newArray:满足 function ( item, index,arr) 的新数组
举例
<body>
<div id="root">
list:
<p v-for="item in list">
{{item.box}}
{{item.textValue}}
{{item.id}}
</p>
list1:
<p v-for="item in list1">
{{item.box}}
{{item.textValue}}
{{item.id}}
</p>
list2:
<p v-for="item in list2">
{{item.box}}
{{item.textValue}}
{{item.id}}
</p>
list3:
<p v-for="item in list3">
{{item.box}}
{{item.textValue}}
{{item.id}}
</p>
</div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
list:[
{ box: false, textValue:'吃早饭',id:0},
{ box: false, textValue:'吃午饭',id:1},
{ box: false, textValue:'吃晚饭',id:2},
{ box: true, textValue:'锻炼',id:3},
{ box: true, textValue:'下棋',id:4},
{ box: true, textValue:'游泳',id:5},
],
}
},
computed:{
list1(){
//item为当前正在处理的元素
return this.list.filter((item)=>item.box === false);
},
list2(){
// index为正在处理元素的索引
return this.list.filter((item,index)=>index>2);
},
list3(){
// arr为调用了filte数组的本身
return this.list.filter((item,index,arr)=>arr[index]);
}
},
});
const vm = app.mount('#root');
</script>
实现效果:
方法特点
- 函数执行次等于 数组长度,也就是原数组中的每一个元素都会执行一次
- 函数内部的return:满足筛选条件,放入新数组中;不满足条件,不放入新数组中
- 方法不会改变原始数组