简体   繁体   English

如何检查vue.js中数组中是否已存在项目?

[英]How to check if item already exists in array in vue.js?

I have this array where i add values on click, but i want to check if value is already in array, if it is do nothing. 我有这个数组,我可以在其中单击添加值,但是我想检查值是否已经在数组中,如果它什么也不做。 I tried with indexOf but i get same result every time 我尝试使用indexOf但每次都得到相同的结果

this.fields.push(this.field);
      this.field = { value: '' };

Are you determining if it's in the array by the value property? 您是通过value属性确定它是否在数组中吗? If so you can use Array.some() . 如果是这样,您可以使用Array.some()

var exists = this.fields.some(function(field) {
  return field.value === this.field.value
});

if (!exists) {
  this.fields.push(this.field);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM