[英]How to compare all nested child elements length with each other?
我有一個包含嵌套子的對象,如下所示:
$scope.artists.materials.items[] //contains list of items
現在我會有幾個藝術家將包含項目列表,但在此我想檢查每個藝術家項目的總長度,如果發現不匹配,那么我想返回真或假。
例如 :我有2個藝術家,從這個Artist1包含2個項目,Artist2只包含1個項目然后這是一個不匹配,因為我想讓藝術家包含相同數量的項目。
但在這里,我對如何以AngularJS方式進行所有這些比較感到困惑。
碼:
function checkItemsValidity() {
angular.forEach($scope.artists, function (artist) {
alert(artist.materials.items.length);
});
}
我怎樣才能更好地做到這一點?
如果所有藝術家必須擁有相同數量的items
,那么只需存儲第一位藝術家的items
長度,並確保所有這些items
都具有相同的items
長度。 就像是:
更新了評論中的建議
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;
}
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.