0

我想对一个在术语(键、值)方面具有关联性的对象进行排序我能够根据 存储值key,但无法在value使用内置sort()函数的基础上对它们进行排序,例如关联数组。

var usernames = {};

username[1] = "ZNAME";
username[2] = "BNAME";
username[3] = "ANAME";
username[4] = "TNAME";
username[5] = "KNAME";
username[5] = "YNAME";

$.each(usernames,function(key, value){
    alert(key + " : " + value);
})

请告诉方法用我更新的 JSFIIDLE 进行排序

演示

4

2 回答 2

1

你不能对一个对象进行排序,你必须把它变成一个数组。例如:

var usernamesArray = [
    {key:1,username:"ZNAME"},
    {key:2,username:"BNAME"},
    ...
    {key:5,username:"YNAME"}
];
var sortedUsernamesArray=usernamesArray.sort(function(a,b){
    //
    return (a.username>b.username)?1:-1;
});

现场演示:http: //jsfiddle.net/GrD4v/

注意:这里不需要 jQuery。

[编辑] 有几种不同的方法来构建 usernamesArray。一个简单的:

var usernamesObject = {};
var usernamesArray = [];

usernamesObject[1] = "ZNAME";
usernamesObject[2] = "BNAME";
usernamesObject[3] = "ANAME";
usernamesObject[4] = "TNAME";
usernamesObject[5] = "KNAME";
usernamesObject[6] = "YNAME";

for (var i=1;i<7,i++) {
    usernamesArray.push({key:i,username:usernamesObject[i]});
}
于 2013-10-14T22:04:47.427 回答
1
var username = [];

username[0] = "ZNAME";
username[1] = "BNAME";
username[2] = "ANAME";
username[3] = "TNAME";
username[4] = "KNAME";
username[5] = "YNAME";

username.sort();

$.each(username,function(key, value){
    alert(key + " : " + value);
})
于 2013-10-14T21:44:30.607 回答