Javascript 比较数组中的对象属性

Javascript 比较数组中的对象属性,javascript,arrays,object,Javascript,Arrays,Object,将一组对象存储在数组中。如果我想比较像权重这样的属性,我将如何以最有效的方式进行比较?比方说,当重量=10时,我希望果篮是满的 var fruitBasket = [] function addFruit(fruit, weight) { return { fruit: fruit, weight: weight } } fruitBasket.push(addFruit(apple, 2)); fruitBasket.push(addFruit(orange, 3)); fru

将一组对象存储在数组中。如果我想比较像权重这样的属性,我将如何以最有效的方式进行比较?比方说,当重量=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...

您需要在水果篮数组中的某个位置维护一个权重的总和,在添加之前,您应该根据项目的添加权重进行检查。无需通过数组->对象访问来过多地担心添加项的单个权重,而是让函数来处理它

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  
    }
  }
}
var totalWeight=0,
最大重量=10;
功能添加水果(水果,重量){
//如果重量不超过maxWeight,则将项目添加到果篮中

如果((totalWeight+weight)对于您给出的特定示例,我将使用Array.reduce方法,如下所示:

var weight =fruitBasket.reduce(function(a,b){return a.weight + b.weight})
这会给你总的重量。 减少信息()


但是,答案可能取决于您所指的有效性(即效率、最佳性能、可读性等)

使用
Array.prototype.reduce
,使用添加
权重属性的函数。