猿问

js写了个按属性排序的方法,运行的结果没排序?

试了下这个是好使的:


arr.sort(function(a,b){return a-b})

可以把数组从小到大排序


     var data=[

            {name:"hhhh",age:17,else:200},

            {name:"ssss",age:18,else:100}

        ]


     function compareSth(name){

        return function(obj1,obj2){

            var  value1 = obj1[name];

            var  value2 = obj2[name];

            if(value1 < value2){

                return -1;

            }else if(value2 > value1){

                return 1;

            }else{

                return 0;

            }

        }

     }

     data.sort(compareSth("age"));

     console.log(data);

    data.sort(compareSth("else"));

     console.log(data);

     data.sort(compareSth("name"));

     console.log(data);

那这个为啥不能按属性的大小排呐。。。看不出啥问题


慕哥9229398
浏览 347回答 1
1回答

陪伴而非守候

你确定?你的if 和else if的条件不是相同的吗var data=[&nbsp; &nbsp; {name:'iiii',age:20,else:300},&nbsp; &nbsp; {name:"hhhh",age:17,else:200},&nbsp; &nbsp; {name:"ssss",age:18,else:100}&nbsp; &nbsp; ]&nbsp; &nbsp; function compareSth(name){&nbsp; &nbsp; &nbsp; &nbsp; return function(obj1,obj2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var&nbsp; value1 = obj1[name];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var&nbsp; value2 = obj2[name];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(value1 < value2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if(value1 > value2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(data.sort(compareSth('age')));你试一试,没问题的
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答