首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

请javascript高手解决一下这个array.sort 的有关问题

2012-04-19 
请javascript高手解决一下这个array.sort 的问题function sortByFoo(tab){// TODO: Fill in the code here

请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); 

热点排行