Javascript排序未执行的对象数组

时间:2016-01-23 09:46:01

标签: javascript arrays sorting

我必须对一组对象进行排序,并且我已经编写了代码,但它并没有执行。数组是相同的,当我查看我的调试器控制台时,它会跳转到下一个函数并且不执行我的排序。我尝试过很多东西,但似乎没什么用。也许我忽视了一些事情,但我希望有人知道它为什么不能执行。

我的代码:

function orderData(toSort) {
    console.dir(toSort);
    toSort.sort(compareCountries);

    console.dir(toSort);
    return toSort;
}
function compareCountries(a, b) {
    var avgx = 0;
    var avgy = 0;

    avgx = calcAvgForAllProperties(a, avgx);
    avgy = calcAvgForAllProperties(b, avgy);

    a["overalAvg"] = avgx;
    b["overalAvg"] = avgy;

    if (a.overalAvg > b.overalAvg)
        return -1;
    else if (b.overalAvg < a.overalAvg)
        return 1;
    else
        return 0;
}

或:

function orderData(toSort) {
    console.dir(toSort);
    toSort.sort(function (a, b) {
        var avgx = 0;
        var avgy = 0;

        avgx = calcAvgForAllProperties(a, avgx);
        avgy = calcAvgForAllProperties(b, avgy);

        a["overalAvg"] = avgx;
        b["overalAvg"] = avgy;

        if (a.overalAvg > b.overalAvg)
            return -1;
        else if (b.overalAvg < a.overalAvg)
            return 1;
        else
            return 0;
    });

    console.dir(toSort);
    return toSort;
}

// EDIT 以下是我的数据示例:

Data example

1 个答案:

答案 0 :(得分:1)

您的代码存在以下问题:

  1. 排序功能有副作用
  2. 您不应在overallAvg中计算compareCountries。相反,您应该在排序之前执行此操作。

        var countries = [ /* your countries */ ];
    
        countries.forEach(calculateCountryOverallFooAverage); // Standard forEach is not chainable.
        countries.sort(compareCountriesByOverallFooAverage);
    
        function calculateCountryOverallFooAverage(country) {
            country.calculateOverallFooAverage();
        }
    
        function compareCountriesByOverallFooAverage(lhs, rhs) {
            var lhsAvg = lhs.overallFooAverage();
            var rhsAvg = rhs.overallFooAverage();
    
            if (lhsAvg < rhsAvg) { return -1; }
            else if(lhsAvg > rhsAvg) { return 1; }
            return 0;
        }
    
    1. 比较不正确,因为第二个测试与第一个测试相同(你做if (a < b) {} else if (b > a) {} else {})。它应该是:

      if (a.overalAvg > b.overalAvg) return -1;
      else if (a.overalAvg < b.overalAvg) return 1;
      else return 0;