如果数组中的所有对象都具有属性值,则返回true(return true if all objects in array has value in property)
我有一个对象数组,如下所示:
$scope.objectArray = [ {Title: 'object1', Description: 'lorem', Value: 57}, {Title: 'object2', Description: 'ipsum', Value: 32}, {Title: 'object3', Description: 'dolor', Value: 135} ]我想检查并返回true,如果此数组中的所有对象在属性“值”内都有一个值。
我想我可以用forEach循环来做,但是有没有比这更好的方法?
var isTrue = true; angular.forEach(objectArray, function(o){ if (!o.Value){ isTrue = false; // change variable 'isTrue' to false if no value } });I have an array of objects, something like this:
$scope.objectArray = [ {Title: 'object1', Description: 'lorem', Value: 57}, {Title: 'object2', Description: 'ipsum', Value: 32}, {Title: 'object3', Description: 'dolor', Value: 135} ]I would like to check, and return true, if all objects in this array has an value inside the property 'value'.
I think I could do it with an forEach loop, but is there a better way than this?
var isTrue = true; angular.forEach(objectArray, function(o){ if (!o.Value){ isTrue = false; // change variable 'isTrue' to false if no value } });最满意答案
只要使用Array#every() ,如果0不计数。
var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 57 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] }, isTrue = $scope.objectArray.every(function (a) { return a.Value; }); document.write(isTrue);将0作为值进行测试的解决方案。
var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 0 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] }, isTrue = $scope.objectArray.every(function (a) { return a.Value || a.Value === 0; }); document.write(isTrue);Just use Array#every(), if 0 does not count.
var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 57 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] }, isTrue = $scope.objectArray.every(function (a) { return a.Value; }); document.write(isTrue);Solution with test for 0 as a value.
var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 0 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] }, isTrue = $scope.objectArray.every(function (a) { return a.Value || a.Value === 0; }); document.write(isTrue);
更多推荐
发布评论