Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 搜索淘汰数组以查找重复条目_Javascript_Arrays_Knockout.js - Fatal编程技术网

Javascript 搜索淘汰数组以查找重复条目

Javascript 搜索淘汰数组以查找重复条目,javascript,arrays,knockout.js,Javascript,Arrays,Knockout.js,我有一个名为self.Employees的KO数组,它有一个显示在屏幕上的用户名列表。用户可以向系统输入新用户,如果名称已经在数组中,我想抛出一个错误。如果文本框为空,我可以抛出一个错误,但是我似乎无法正确地进行搜索。下面是我尝试过的代码 var employeeList = [ new Employee(1, "Jack Johnson"), new Employee(2, "Alice Smith"), new Employee(3, "Clark Kent"),

我有一个名为self.Employees的KO数组,它有一个显示在屏幕上的用户名列表。用户可以向系统输入新用户,如果名称已经在数组中,我想抛出一个错误。如果文本框为空,我可以抛出一个错误,但是我似乎无法正确地进行搜索。下面是我尝试过的代码

  var employeeList = [
    new Employee(1, "Jack Johnson"),
    new Employee(2, "Alice Smith"),
    new Employee(3, "Clark Kent"),
    new Employee(4, "Bruce Banner"),
    new Employee(5, "Alan Moore")
  ];
self.Employees=ko.observearray(employeeList)//要求

      var match = ko.utils.arrayFirst(self.Employees, function(item)
        {
          return item.employeeName == employee.Name;
        });

    if(match === employee.Name) {
        self.error("Duplicate entry.");
        return;
      }



      // Check if a field is blank before adding to array THIS WORKS
      if(employee.Name == "") {
        self.error("A new employee name is required.");
        return;
      }
      else {
        self.error("");
      }
您可以尝试使用“some”函数来检查它是否存在于对象数组中。 它也可能更干净

var name = "check if this name exists"

var itExists = arrayOfObjects.some(employee => employee.name === name);


如果名称位于对象数组中,则这将成为事实,因为任何员工的名称都在该数组中

我认为您的代码的问题在于
match
被设置为员工对象,因此不能像这样进行比较:

// Wrong
if (match === employee.Name) { }
相反,您可以尝试:

// Right
if (match && match.Name === employee.Name) { }

如果您想进行更多重构,我建议将
newEmployeeValid
实现为
pureComputed
属性。这里有一个例子

职能员工(id、姓名){
this.name=ko.observable(name);
this.id=id;
}
功能应用程序(员工){
this.employeeList=ko.observearray(员工);
this.newEmployeeName=ko.可观察(“”);
this.nameValid=ko.pureComputed(
()=>this.newEmployeeName().length>1
);
this.nameUnique=ko.pureComputed(
()=>!this.employeeList()。一些(
other=>other.name()==this.newEmployeeName()
)
);
this.error=ko.pureComputed(
() => {
如果(!this.nameValid())
return`名称应包含1个以上字符';
如果(!this.nameUnique())
return`我们已经有一个名为${this.newEmployeeName()}的员工`
返回null;
}
)
this.employeeValid=ko.pureComputed(
()=>!!此.错误()
);
this.addEmployee=()=>{
这是.employeeList.push(
新员工(null,this.newEmployeeName())
)
}
};
ko.applyBindings(新应用程序([
新员工(1名,“杰克”),
新员工(2名,“Alice”),
新员工(3,“克拉克”),
新员工(4名,“Bruce”),
新员工(5名,“艾伦”)
]));

添加

我似乎仍面临一些挑战。也许我做错了什么。我将用有关KO数组的附加信息更新代码