我想獲得一個簡單的排序工作的對象數組,但它似乎是返回完全隨機的結果。請看看這個普拉克(在FF或Chrome)JavaScript的對象數組排序返回隨機結果
http://plnkr.co/edit/TqoyUJV4nzvC4hAkVRkz?p=preview
var data;
var asc;
function init(){
data = [{username:"leonhaas"},{username:"0johnson"},{username:"leonlang"},{username:"0lechner"},{username:"0koller"},{username:"leonwinkler"},{username:"0schmidt"},{username:"0mueller"},{username:"0schmid"},{username:"lillyfuchs"},{username:"alexandragruber"},{username:"alexanderlechner"},{username:"alexanderpichler"},{username:"alexandraeder"},{username:"lillyreiter"},{username:"alibauer"},{username:"alexandrahall"},{username:"alexandrajohnson"},{username:"alexandrataylor"},{username:"alexandrawilliams"},{username:"lilywinkler"},{username:"alinabauer"},{username:"aliceegger"},{username:"alicesteiner"},{username:"alicewallner"},{username:"aliegger"},{username:"alifuchs"},{username:"linajohnson"},{username:"amarwhite"},{username:"alinaleitner"},{username:"alinaschmidt"},{username:"alinawood"},{username:"alischneider"}];
outputData(data);
asc = true;
}
function sortIt()
{
a = data.username;
b = data.username;
if(asc){
data.sort(function(a,b)
{
return 1;
});
} else {
data.sort(function(a,b)
{
return -1;
});
}
outputData(data);
}
function outputData(data){
var output = "";
data.forEach(function (item){
output += item.username +"<br>";
});
var x=document.getElementById("demo");
x.innerHTML=output;
}
謝謝!同時我發現了另一種方式:data.sort(function(a,b) var x = a ['username'],y = b ['username']; return(x == y? 0:(x> y?1:-1)); }); –