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

Non*_*one 3 javascript vue.js vuejs2

我有这个数组,我在点击时添加值,但我想检查值是否已经在数组中,如果它什么都不做。我尝试使用 indexOf 但每次都得到相同的结果

this.fields.push(this.field);
      this.field = { value: '' };
Run Code Online (Sandbox Code Playgroud)

Bil*_*ell 5

您是否通过value属性确定它是否在数组中?如果是这样,您可以使用Array.some().

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

if (!exists) {
  this.fields.push(this.field);
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*ero 5

在对象数组中最好使用 Array.some()

this.users = [{id : 1, name : 'Jonh Doe'},{id : 2, name : 'Mary Jean'}]

if(!this.users.some(data => data.id === 1)){
    //don't exists       
}else{
    //exists because Jonh Doe has id 1
}
Run Code Online (Sandbox Code Playgroud)

来源:https : //www.samanthaming.com/