Vue之判断数组内是否存在某一项

两种方法:

findIndex()和 indexOf()方法

findIndex()顾名思义,查找符合条件的值并返回其索引(返回值为-1表示不存在满足条件的值),通过判断返回值对其进行下一步操作

indexOf()从头开始寻找是否存在符合条件的字符串,返回值为-1表示不存在

//方法一:通用
xx(Arr,date){ 
	// 返回值等于-1 说明数组Arr中不存在id为date的对象
	if( Arr.findIndex(item => item.id=== date )!==-1){
	...
	}	
}

//方法二:当数组里的对象为字符串时用这个方法更简单
xx(Arr,date){
	// 返回值等于-1 说明数组Arr中不存在id为date的对象
	if( Arr.indexOf(date)!==-1 ){
	...
	}	
}
    

实例

xxx(){
      const that=this;
      that.$axios.get('/get_collection_user') //axios请求
        .then((res)=>{
          that.cards = res.data  //获取cards数组
          //判断数组内是否存在数据that.storeId,如果不存在返回值为-1
          if(that.cards.findIndex(item => item.mindId=== that.storeId)!==-1){  
            that.isActive = true
          }
      })

你可能感兴趣的:(vue,JavaScript,vue.js,前端,javascript)