如果数组中的所有对象都具有属性值,则返回true(return true if all objects in array has value in property)

编程入门 行业动态 更新时间:2024-10-25 16:23:47
如果数组中的所有对象都具有属性值,则返回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); 
  
 

更多推荐

本文发布于:2023-08-07 08:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   属性   对象   true   property

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!