gpt4 book ai didi

Javascript 对象数组排序返回明显随机的结果

转载 作者:行者123 更新时间:2023-11-30 08:51:11 25 4
gpt4 key购买 nike

我正在尝试对对象数组进行简单排序,但它似乎返回完全随机的结果。请看看这个 plunk:(在 FF 或 Chrome 中)

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;
}

最佳答案

在排序函数中,您必须比较数据对象的用户名:

function sortIt()
{
if(asc){
data.sort(function(a,b)
{
return a.username.localeCompare(b.username);
});
} else {
data.sort(function(a,b)
{
return b.username.localeCompare(a.username);
});
}

outputData(data);
}

关于Javascript 对象数组排序返回明显随机的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17717558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com