angularjs forEach和splice [英] angularjs forEach and splice
本文介绍了angularjs forEach和splice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样一个数组:
$scope.emails = [
{"key":"Work","value":"user@domine.com"},
{"key":"","value":""},
{"key":"Work","value":"user2@domine.com"}
{"key":"","value":""}];
所以,我想删除空的电子邮件,但是角度 forEach
方法只删除一个对象为最后一个对象的原因???。
So, I want to remove empty emails but angular forEach
method removing only one object that is last object why???.
js code
angular.forEach($scope.emails, function(email, index){
if(email.value ===""){
$scope.emails.splice(index, 1);
}
});
我做错了
< a href =http://jsbin.com/waxenusa/3/> JS Bin
推荐答案
问题是你在循环期间从数组中删除元素,以便后面的项目处于不同的索引。你需要向后循环:
The problem is that you remove elements from the array during the loop so later items are at different indices. You need to loop backwards instead:
for (var i = $scope.emails.length - 1; i >= 0; i--) {
if (!$scope.emails[i].value) {
$scope.emails.splice(i, 1);
}
}
这是更新示例。
这篇关于angularjs forEach和splice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文