早上好,
我想将新项目推送到一个数组(我们可以这样做),但在推送检查重复项以防止在数组中复制项目之前。
我试过这个 example ,失败了,我还没有设法让我们的代码工作。
如果有人知道更好的解决方案或可以看到我们哪里出错了,请尽快告诉我们。
谢谢你。
** JS **
$scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
$scope.logItem = function($index, brandName, partNumber, productName, amount) {
$scope.newItem = {
Brand: brandName,
Part: partNumber,
Product: productName,
Amount: amount
};
var duplicateItem = $scope.Products.reduce(function(previous, i) {
if ($scope.newItem === i) return true;
return previous
}, false);
if (duplicateItem) {
alert("Already Logged");
} else {
alert("Item Logged");
$scope.Products.push($scope.newItem);
$scope.$storage.Products = $scope.Products;
}
}
** 使固定 **
$scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products;
$scope.logItem = function($index, brandName, partNumber, productName, amount) {
$scope.newItem = {
Brand: brandName,
Part: partNumber,
Product: productName,
Amount: amount
};
var isDuplicate = false;
$scope.Products.forEach(function(element) {
if (JSON.stringify(element) === JSON.stringify($scope.newItem)) {
isDuplicate = true;
return false;
}
});
if (!isDuplicate) {
alert("Item Logged");
$scope.Products.push($scope.newItem);
$scope.$storage.Products = $scope.Products;
} else {
alert("Already Logged");
};
}
最佳答案
像这样的东西
$scope.Products.forEach(function (element) {
if (JSON.stringify(element) === JSON.stringify($scope.newItem)) {
isDuplicate = true;
return false;
}
});
Look fiddle
关于arrays - 推送前检查重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27225123/