我需要阻止在$scope.EmployeeList
数组中插入重复的Rec为我写的($scope.EmployeeList.indexOf(EmpDetails) == -1)
但是它没有过滤我的rec
$scope.EmployeeList = [];
var amtArray = [];
$scope.G_Total = "Total Amount is";
$scope.SaveDb = function (Isvalid) {
var EmpDetails = {
'EmpName': $scope.EmpName,
'Email': $scope.Email,
'Cost': $scope.cost
}
if ($scope.EmployeeList.indexOf(EmpDetails) == -1) {
$scope.EmployeeList.push(EmpDetails);
console.log($scope.EmployeeList);
}
else
alert('Duplicate Value....');
答案 0 :(得分:1)
不要使用 indexOf (它会检查严格的相等性),请尝试 findIndex :
if ($scope.EmployeeList.findIndex(function(e) { return e.EmpName === EmpDetails.EmpName; }) === -1) {
$scope.EmployeeList.push(EmpDetails);
console.log($scope.EmployeeList);
}
答案 1 :(得分:1)
您还可以使用Array.prototype.some
查找重复值。some()
方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。
var empDetails = {name: 'abc', email: 'a@gmail.com'};
let duplicate = $scope.EmployeeList.some(function (emp) {
return emp.name === empDetails.name && emp.email === empDetails.email;
});
if (!duplicate) {
$scope.EmployeeList.push(EmpDetails);
}
else
alert('Duplicate Value....');