JS-数组⽅法filter中使⽤return及es6的newSet()
1. 项⽬中看到过滤数组的⼀个⽅法,就想着学习下数组的filter⽅法和es6的new Set
2. 项⽬代码如下:就是给数组去重,去掉数组中重复的id;
msgList(){
// 对 whatsAppMsgList 做 messageId 去重
let msgList =this.whatsAppMsgList.slice();
const ids =new Set();
msgList = msgList.filter(item =>{
if(!ids.ssageId)){
ids.ssageId);
return true;
}
});
console.log(msgList);
return msgList;
},
3. arr.filter()⽅法时js中数组的⼀个⽅法,括号中接收⼀个函数,根据函数中的规则,对数组进⾏操作,该⽅法不会对原数组造成影响;0
var arr =[1,2,3,4,5,6,7,8,5,6,7,8];
arr=arr.filter(item=>{
item >5
})
1
var arr =[1,2,3,4,5,6,7,8,5,6,7,8];
arr2 = arr.filter(item=>{
return item >5
})
arr2 [6,7,8,6,7,8]
2
var arr =[1,2,3,4,5,6,7,8,5,6,7,8];
arr=arr.filter(item=>{
if(item >5){
return true
filter过滤对象数组}
})
(6)[6,7,8,6,7,8]
3
var arr =[1,2,3,4,5,6,7,8,5,6,7,8];
arr2=arr.filter(item=>{
if(item >5){
return true
}
});
console.log(arr,arr2);
VM567:1(12)[1,2,3,4,5,6,7,8,5,6,7,8](6)[6,7,8,6,7,8];
(6)[6,7,8,6,7,8]
4
var arr =[1,2,3,4,5,6,7,8,5,6,7,8];
let ids =new Set();
arr2=arr.filter(item=>{
if(!ids.has(item)){
ids.add(item);return true
}
});
console.log(arr,arr2)
(12)[1,2,3,4,5,6,7,8,5,6,7,8](8)[1,2,3,4,5,6,7,8]
var arr =[1,2,3,4,5,6,7,8,5,6,7,8];
var ids1 =new Set();
arr2 = arr.filter(item =>{
if(!ids1.has(item))
{ids1.add(item);
return true;}
});
console.log(arr,arr2);// [1, 2, 3, 4, 5, 6, 7, 8, 5, 6, 7, 8] (8) [1, 2, 3, 4, 5, 6, 7, 8];
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论