[英]How to compare all nested child elements length with each other?
I have 1 object which contains nested child like below: 我有一个包含嵌套子的对象,如下所示:
$scope.artists.materials.items[] //contains list of items
Now I would have several artist which will contains list of items but in this I want to check total length of each item of artists and if mismatch found then I want to return true or false. 现在我会有几个艺术家将包含项目列表,但在此我想检查每个艺术家项目的总长度,如果发现不匹配,那么我想返回真或假。
For eg : I have 2 artist and from this Artist1 contains 2 items and Artist2 contains only 1 item then this is a mismatch as I want to have both the artist to contains same number of items. 例如 :我有2个艺术家,从这个Artist1包含2个项目,Artist2只包含1个项目然后这是一个不匹配,因为我想让艺术家包含相同数量的项目。
But here I am confused with how do i do all this comparison in AngularJS way. 但在这里,我对如何以AngularJS方式进行所有这些比较感到困惑。
Code: 码:
function checkItemsValidity() {
angular.forEach($scope.artists, function (artist) {
alert(artist.materials.items.length);
});
}
How can I do this in better way? 我怎样才能更好地做到这一点?
If all artists have to have the same number of items
, then just store the length of the items
from the first artist and make sure all of them have that same items
length. 如果所有艺术家必须拥有相同数量的
items
,那么只需存储第一位艺术家的items
长度,并确保所有这些items
都具有相同的items
长度。 Something like: 就像是:
Updated with suggestions from comments 更新了评论中的建议
function checkItemsValidity() {
var itemsLength = $scope.artists[0].materials.items.length;
angular.forEach($scope.artists, function (artist) {
if(artist.materials.items.length != itemsLength) {
return false;
}
});
return true;
}
An improvement to Lex's answer: no need for the isValid
variable, if there's no reason to go through the rest once the first difference is found. Lex答案的改进:如果找到第一个差异,如果没有理由通过其余部分,则不需要
isValid
变量。
function checkItemsValidity() {
var len = $scope.artists[0].materials.items.length;
for (var i = 0; i < $scope.artists.length; i++) {
if ($scope.artists[i].materials.items.length != len) {
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.