相关疑难解决方法(0)

更好地计算数组中属性值的方法

我有这样的事情:

$scope.traveler = [
            {  description: 'Senior', Amount: 50},
            {  description: 'Senior', Amount: 50},
            {  description: 'Adult', Amount: 75},
            {  description: 'Child', Amount: 35},
            {  description: 'Infant', Amount: 25 },
];
Run Code Online (Sandbox Code Playgroud)

现在有了这个数组的总量,我正在做这样的事情:

$scope.totalAmount = function(){
       var total = 0;
       for (var i = 0; i < $scope.traveler.length; i++) {
              total = total + $scope.traveler[i].Amount;
            }
       return total;
}
Run Code Online (Sandbox Code Playgroud)

当只有一个数组时很容易,但我有其他数组,我想要总结一个不同的属性名称.

我会更高兴如果我可以做这样的事情:

$scope.traveler.Sum({ Amount });
Run Code Online (Sandbox Code Playgroud)

但我不知道如何通过这种方式来解决这个问题,我可以在将来重复使用它,如下所示:

$scope.someArray.Sum({ someProperty });
Run Code Online (Sandbox Code Playgroud)

回答

我决定使用@gruff-bunny建议,所以我避免原型对象(Array)的原型设计

我只是对他的答案做了一点修改,验证了数组,并且sum的值不为null,这是我的最终实现:

$scope.sum = function (items, prop) {
    if …
Run Code Online (Sandbox Code Playgroud)

javascript arrays prototype-programming

136
推荐指数
13
解决办法
15万
查看次数

标签 统计

arrays ×1

javascript ×1

prototype-programming ×1