日期:2014-05-16  浏览次数:20393 次

请javascript高手解决一下这个array.sort 的问题
function sortByFoo(tab)
{
  // TODO: Fill in the code here, using Array.sort.
  
  return tab;
}

// Sort by .foo attribute
console.log(sortByFoo(
  [{foo: 5}, {foo: 7}, {foo: 4}, {foo: 3}, {foo: 2}, {foo: 1}, {foo: 6}]
  )[5].foo === 6);
// Does not crash on an empty array
console.log(sortByFoo([]).length === 0);
// For objects without a `foo` attribute, its value should be considered equal to '0'
console.log(sortByFoo([{foo: 42}, {bar: 7}, {foo: -5}])[1].bar === 7);
要求补充程序,使得在浏览器中显示三次true

------解决方案--------------------
JScript code
function sortByFoo(tab) {
    tab.sort(function (t1, t2) {
        return (t1.foo || 0) - (t2.foo || 0);
    });
    return tab;
}

------解决方案--------------------
JScript code
        function sortByFoo(tab){
            // TODO: Fill in the code here, using Array.sort.
            tab.sort(function(elem1, elem2){
                var foo1 = elem1.foo || 0,
                    foo2 = elem2.foo || 0;
                return foo1 > foo2 ? 1 : foo1 === foo2 ? 0 : -1;
            });
            return tab;
        }
        
        // Sort by .foo attribute
        console.log(sortByFoo(
        [{foo: 5}, {foo: 7}, {foo: 4}, {foo: 3}, {foo: 2}, {foo: 1}, {foo: 6}]
        )[5].foo === 6);
        // Does not crash on an empty array
        console.log(sortByFoo([]).length === 0);
        // For objects without a `foo` attribute, its value should be considered equal to '0'
        console.log(sortByFoo([{foo: 42}, {bar: 7}, {foo: -5}])[1].bar === 7);