jS中的Filter函数
1.作用
filter用于对数组进行过滤。
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
2.语法
Array.filter(function(currentValue, index, arr), thisValue)
其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;
函数的第一个参数 currentValue 也为必须,代表当前元素的值。
3.实例
返回数组nums中所有大于5的元素
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let res = nums.filter((num) => {
return num > 5;
});
console.log(res); // [6, 7, 8, 9, 10]
Vue列表过滤
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../JS/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>遍历数组</h2>
<p><input type="text" placeholder="请输入名字" v-model="keyWord" />
</p>
<ul>
<li v-for='(p,index) in filArr' :key="index">
{{index}}---{{p.name}}--{{p.age}}
</li>
</ul>
</div>
<script type="text/javascript">
var vm = new Vue({
el:'#root',
data:{
keyWord:'',
// 原数组
persons: [
{ id: 1, name: '周杰', age: 21 },
{ id: 2, name: '周杰伦', age: 22 },
{ id: 3, name: '周芷若', age: 23 },
{ id: 4, name: '张杰', age: 24 }
],
//过滤后的数组
filArr:[]
},
//监听属性
watch:{
keyWord:{
immediate:true,
// 过滤数组,
//数组中的每个元素都会执行这个函数。p代表当前元素的值。
//例如现在数组中有四个人,第一次执行时 p 就代表 对象{ id: 1, name: '周杰', age: 21 }
handler(val){
console.log("变化了")
this.filArr = this.persons.filter((p)=>{
return p.name.indexOf(this.keyWord) !== -1;
})
}
}
}
/* computed:{
filPerson(){
//过滤数组
let filtArr = new Array();
filtArr = this.persons.filter((a)=>{
return a.name.indexOf(this.keyWord) !== -1;
})
return filtArr;
}
} */
})
</script>
</body>
</html>