无法验证所有嵌套的子元素长度

时间:2016-09-30 10:37:04

标签: javascript angularjs

我有一个包含嵌套子项的对象,如下所示:

$scope.artists.materials.items[] 

现在我会有几个艺术家将包含项目列表,但在此我想检查每个艺术家项目的总长度,如果发现不匹配,那么我想返回真或假。

  

问题是,当时我还没有任何艺术家的物品   我变得虚假

这里的想法是存储第一位艺术家的项目长度,并确保所有项目都具有相同的项目长度。

代码:

function checkItemsValidity() {
      for (var i = 1; i < $scope.artists.length; index++) {
            if ($scope.artists[i].materials.items != undefined && $scope.artists[0].materials.items) {
                if($scope.artists[i].materials.items.length != $scope.artists[0].materials.items[0].length) {
                             return false;
                }
            }        
                             return false;
        }
            return true;
    }

案例1 :如果只有1位艺术家,则返回true,因为没有其他艺术家可以比较

案例2 :如果2位艺术家同时为两位艺术家提供2项,则返回true,否则为false;

案例3 :如果有3位艺术家,其中2位为artist1,艺术家为2,5位为artist3,则返回false;

有人可以用这个来发牢骚吗?

7 个答案:

答案 0 :(得分:4)

据我了解,您只想检查每位艺术家是否拥有相同数量的商品。这段代码:

var result, materialsNumber;
for (var artist of $scope.artists) {
   var artistMaterialsNumber = artist.materials.items.length;
   if (!materialsNumber) {
       materialsNumber = artistMaterialsNumber;
   }
   result = (materialsNumber === artistMaterialsNumber);
   if (!result) {
      break;
   }
}

return result;

应该对此有用。它记住第一位艺术家的项目数量,并检查每个其他艺术家是否有相同数量的项目。如果艺术家有不同的商品编号代码中断并返回false

答案 1 :(得分:2)

您好,您也可以尝试一下......

var vFirstItemLength = artists[0].materials.items.length;
result = (artists.filter(function(item){return item.materials.items.length===vFirstItemLength;}).length === (artists.length));

答案 2 :(得分:1)

var artists = [{
	materials: {
		items: [1, 2, 3]
	}
}, {
	materials: {
		items: [1, 3]
	}
}, {
	materials: {
		items: [1, 2, 3]
	}
}, {
	materials: {}
}];

artists.some(function(artist, i) {
	if (i === 0) return false;
	if (artists.length === 1) {
		console.log("Index " + i);
		console.log(true);
		return true; // length is one
	}
	if (artists[0].materials.items) {
		if (!artist.materials.items) {
			console.log("Index " + i);
			console.log(false);
			return false; // items doesn't exist. Return true/false, whatever works for you
		} else if (artist.materials.items &&
			artist.materials.items.length === artists[0].materials.items.length) {
			console.log("Index " + i);
			console.log(true);
			return true; // length is equal
		} else {
			console.log("Index " + i);
			console.log(false);
			return false; // length is unequal
		}
	} else {
		if (artist.materials.items) {
			console.log("Index " + i);
			console.log(false);
			return false; // one has  items, other doesn't
		} else {
			console.log("Index " + i);
			console.log(true);
			return true; // both have no items
		}

	}
});

你为什么不试试

artists.some(function(artist, i) {
    if (i === 0) return false;
    if (artists.length === 1) {
        console.log("Index " + i);
        console.log(true);
        return true; // length is one
    }
    if (artists[0].materials.items) {
        if (!artist.materials.items) {
            console.log("Index " + i);
            console.log(false);
            return false; // items doesn't exist. Return true/false, whatever works for you
        } else if (artist.materials.items &&
            artist.materials.items.length === artists[0].materials.items.length) {
            console.log("Index " + i);
            console.log(true);
            return true; // length is equal
        } else {
            console.log("Index " + i);
            console.log(false);
            return false; // length is unequal
        }
    } else {
        if (artist.materials.items) {
            console.log("Index " + i);
            console.log(false);
            return false; // one has  items, other doesn't
        } else {
            console.log("Index " + i);
            console.log(true);
            return true; // both have no items
        }

    }
});

答案 3 :(得分:1)

由于所有艺术家都需要拥有相同数量的材料......

function checkMaterials (arists)
{
  if (!artists || !artists.length) { return false; }
  if (artists.length < 2)          { return true; }

  var valid = true;
  var materialCount

  try
  {
    //All artists must have the same number of materials, so we
    //can test against the number of materials that the first
    //artist has and reduce the number times we access the object
    materialCount = (artists[0].materials.items || []).length;
  }
  catch (exception)
  {
    //Object is malformed
    return false;
  }

  //Loop through the remaining artists and check how
  //many materials they have against the first artist
  for (var i = 1; i < artists.length; i++)
  {
    if (!artists[i].materials || ((artists[i].materials.items || []).length !== materialCount)
    {
      //Once one failed case is found, we can stop checking
      valid = false;
      break;
    }
  }

  return valid;
}

//Test data
var validArtists = [{
  materials: {
    items: [1, 2, 3]
  }
}, {
  materials: {
    items: [1, 3, 4]
  }
}];

var invalidArtists = [{
  materials: {
    items: [1, 2]
  }
}, {
  materials: {
    items: [3]
  }
}];

//Tests
console.log (checkMaterials (validArsists)); //Prints true
console.log (checkMaterials (invalidArtists)); //Prints false

答案 4 :(得分:1)

应该解决问题:

function checkValidity() {
    var itemsCounts = $scope.artists.map(function(artist) { return artist.materials.items.length; });
    return itemsCounts.length > 1
        ? itemsCounts.every(function(count) { return count === itemsCounts[0]; })
        : true;
}

答案 5 :(得分:1)

可能你可以这样做;

var artists = [{ materials: { items: [1, 2, 3] } },
               { materials: { items: [1, 2] } },
               { materials: { items: [] } },
               { materials: { items: [1] } },
               { materials: { items: [1, 2, 3] } }
              ];
     result = artists.map(artist => artist.materials.items.length)
                     .every(length => length === artists[0].materials.items.length);
console.log(result);

var artists = [{ materials: { items: [1, 2, 3] } }
              ];
     result = artists.map(artist => artist.materials.items.length)
                     .every(length => length === artists[0].materials.items.length);
console.log(result);

答案 6 :(得分:1)

解决方案:

function checkItemsValidity() {
  if ($scope.artists.length === 1) {
      return true;
  }

  for (var i = 0; i < $scope.artists.length; i++) {
    //this condition might be unnecessary, I assumed items can be undefined from your code.
    if (typeof $scope.artists[i].materials.items === 'undefined') {
        $scope.artists[i].materials.items = [];
    }
    if (i === 0) {
        continue;
    }
    if ($scope.artists[i].materials.items.length !== $scope.artists[0].materials.items.length) {
        return false;
    }
  }

  return true;
}

还有一些测试:https://jsfiddle.net/6x7zpkxe/1/