我需要验证我要添加到对象数组中的对象不存在于临时对象数组中。
Angula JS 抛出错误不允许在转发器中重复。但使用 try/catch 无法捕获此错误。
是否可以检查此类异常或检查对象数组中是否已存在?
感谢您的帮助。
代码示例:
$scope.availableSounds = [
{
name: "Rain"
},
{
name: "Storm"
},
{
name: "Forest"
},
];
$scope.selectedSounds = [];
添加项目(所选声音数组中的对象应该是唯一的)
$scope.addSoundToSelection = function(index) {
try {
var selectedItem = $scope.availableSounds[index];
$scope.selectedSounds.push(selectedItem);
var pos = $scope.selectedSounds.map(function(e) { return e.hello; }).indexOf(selectedItem.name);
console.log(pos);
} catch(e) {
$scope.showAlert();
}
};
最佳答案
indexOf方法怎么样
var myObjectToAdd = {};
var myArray = [ {}, {} ] //some array of objects
if (myArray.indexOf(myObjectToAdd) < 0) {
myArray.add(myObjectToAdd);
}
或者您可以使用 lodash 库的 _.find
关于javascript - Angular JS - 如何捕获转发器中的重复项不允许异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27725762/