2017-10-16 150 views
1

将一组对象存储在数组中。如果我想比较像重量这样的属性,我将如何以最有效的方式来做到这一点?比方说,我想水果篮是全时体重= 10比较数组中的对象属性

var fruitBasket = [] 
function addFruit(fruit, weight) { 
return { 
    fruit: fruit, 
    weight: weight 
} 
} 
fruitBasket.push(addFruit(apple, 2)); 
fruitBasket.push(addFruit(orange, 3)); 
fruitBasket.push(addFruit(watermelon, 5)); 
//etc... 
+0

使用'Array.prototype.reduce'与功能,增加了'重量'属性。 – Barmar

回答

1

你会需要在一些地方维持水果篮阵列中的权重的总和,并添加之前,你应该检查它反对的增加的重量一个物品。不需要担心通过访问数组 - >对象来添加项目的个体重量,而是让您的函数处理它。

var totalWeight = 0, 
    maxWeight = 10; 

function addFruit(fruit, weight) { 
    // Adds items to the fruit basket iff weight does not exceed maxWeight 
    if((totalWeight + weight) <= maxWeight) { 
    totalWeight += weight; 
    return { 
     fruit: fruit, 
     weight: weight 
    } 
    } 
} 
1

你给我会用Array.reduce方法如下具体的例子:

var weight =fruitBasket.reduce(function(a,b){return a.weight + b.weight}) 

这将使你的整体重量。 减少信息(https://www.w3schools.com/jsref/jsref_reduce.asp

然而,答案可能取决于你的意思是有效(即高效率,最佳性能,最可读的等)