javascript - Angular JS - 如何捕获转发器中的重复项不允许异常

标签 javascript arrays angularjs

我需要验证我要添加到对象数组中的对象不存在于临时对象数组中。

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/

相关文章:

javascript - 删除新结果输出开头的逗号

javascript - 如何使用 jQuery 将分钟转换为小时/分钟并将各种时间值加在一起?

python - 从数组中删除前导/尾随零的索引

javascript - 再次触发时计时器速度会加快两倍

javascript - 使用 jQuery 过滤嵌套 JSON 中的空值

javascript - CSS 图像没有覆盖整个屏幕

ios - 如何使用 Swift 4 验证数组中的特定键值

windows-8 - "Unable to add dynamic content"使用 AngularJS for Windows Store App,但它有效

javascript - 如何通知 AngularJS Jquery 插件所做的更改?

angularjs Controller 执行两次