我有一组对象-像这样:

[
  {"name" : "blar", "percentageTotal" : "10", "mostPopular" : "false", "leastPopular" : "false"},
  {"name" : "foo", "percentageTotal" : "40", "mostPopular" : "false", "leastPopular" : "false"},
  {"name" : "bar", "percentageTotal" : "50", "mostPopular" : "false", "leastPopular" : "false"}
]


基于“ percentageTotal”属性,迭代对象并更新“ mostPopular”和“ leastPopular”属性的最佳方法是什么?

最佳答案

一次通过最大/最小“ percentageTotal”找到最受欢迎和最不受欢迎商品的索引,将最受欢迎/最不受欢迎的属性设置为false,然后从存储的索引中设置最受欢迎/最不受欢迎的项目。

function updatePopularity(items) {
  // Find the min/max popularity by percentage total.
  var min=null, max=null, i;
  for (i=0; i<items.length; i++) {
    items[i].mostPopular = items[i].leastPopular = false;
    if (!max || (items[i].percentageTotal > max.pct)) {
      max = {idx:i, pct:items[i].percentageTotal};
    }
    if (!min || (items[i].percentageTotal < min.pct)) {
      min = {idx:i, pct:items[i].percentageTotal};
    }
  }
  // Set the most/least popular values.
  items[max[idx]].mostPopular = true;
  items[min[idx]].leastPopular = true;
}


此解决方案不需要名称唯一。通过设置it=items[i]并改用它,可能会获得较小的性能提升。

关于javascript - 计算出一系列对象中最受欢迎和最不受欢迎的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5470153/

10-09 02:01