• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
kikia
博客园    首页    新随笔    联系   管理    订阅  订阅
判断两个数组中的相同项

vue框架下

this.AllAuthorityOptions=["11","22","33","44","55","管理"];

this.checkedAuthority=["11","33","管理"]
用数组this.checked[index]值记录判断结果,相等true,不等false;,如下设置默认false:
for(let item of this.AllAuthorityOptions) {
  this.checked.push(false);//设置默认false
}
 
判断两个数组的相同项:
方法1用indexof:
for(var i=0;i<this.Options.length;i++){
    if(this.checkedAuthority.indexOf(this.Options[i]) != -1){
        this.checked[i]=true;
    }else{
        this.checked[i]=false;
    }
}
console.log(this.checked+'this.checked111');
 
方法2用vue.map():
this.Options.map((item,index)=>{
  this.checkedAuthority.map((item1,index1)=>{//再判断有相同项的状态为1
    if(item == item1){
      this.checked[index] = true;
    }
  })
})
 
结果:console.log(this.checked);//[true,true,false,false,false,true]
 
如果数组中的元素是对象,方式如下: 

数组1
var arr1 = [
  {id:'1',name:'第一项'},
  {id:'2',name:'‘第二项’'},
  {id:'3',name:'第三项 ' },
];
数组2
var arr2 = [
  {id:'1',name:'第一项'},
  {id:'3',name:'第二项},
]

var arr = arr1.map((item,index)=>{
  item.state = 0;//先设置所有的状态为0
  arr2.map((item1,index1)=>{//再判断有相同项的状态为1
    if(item.name == item1.name){
      item.state = 1;
    }
})
  return item;
})

结果:console.log(arr)可见:[{id:'1',name:'第一项','state':'1'},{id:'1',name:'第一项','state':'0'},{id:'1',name:'第一项','state':'1'}]

 

 

posted on 2019-03-20 17:43  gogo0  阅读(1557)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3