数组 – 在推送之前检查重复的项目
发布时间:2020-12-17 17:55:59 所属栏目:安全 来源:网络整理
导读:早上好, 我想将新项目推送到一个数组(我们可以做),但在推送检查重复项之前,以防止重复数组中的项目. 我已经尝试过这个example,但是没有成功,我没有设法使用我们的代码. 如果有人知道更好的解决方案或者可以看到我们出错的地方,请尽快告诉我们. 谢谢. ** JS *
早上好,
我想将新项目推送到一个数组(我们可以做),但在推送检查重复项之前,以防止重复数组中的项目. 我已经尝试过这个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; } } ** FIX ** $scope.Products = $scope.$storage.Products == undefined ? [] : $scope.$storage.Products; $scope.logItem = function($index,amount) { $scope.newItem = { Brand: brandName,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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |