在排序之前,我可以通过键正确访问数组值。
var a=[];
a['1']={'id':'1','aaa':'xxx'}
a['2']={'id':'2','bbb':'yyy'}
document.write(a['1'].id+' '+a['2'].id+'<br>')
排序后,键变成索引:
a.sort(function(a, b) {
var x = a.id;
var y = b.id;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
alert('a["1"]='+a['1'].id+'\n\na["2"]='+a['2'])
a["2"] 变为未定义。哪里有问题?排序是否错误?
这是一个例子: http://jsfiddle.net/TJLtS/1/
最佳答案
你的问题是 JavaScript 中的数组是从 0 开始的,而不是从 1 开始的。排序后,第一个元素是 a[0]
,第二个元素是 a[1]
。排序后没有a[2]
。
如果您在浏览器中打开开发人员工具,您可以自己看到这一点 - 所有现代浏览器都有它们;如果您需要帮助找到它,请 Google 并在排序后添加代码 console.log(a)
。使用 alert
是调试代码的最痛苦且效率最低的方法。
这是脚本的更新版本,正在运行: http://jsfiddle.net/TJLtS/2/
此外,为了将来的引用,您可能希望更简单地声明对象文字:
var a = [
{id:'1', aaa:'xxx'}, // This is a[0]
{id:'2', bbb:'yyy'} // This is a[1]
];
如您所见,作为合法标识符的键不需要在对象文字中加引号。
编辑根据您的需要,您可能会对以下两种替代方案感兴趣:
将所有对象保留在排序数组中
var objects = [
{id:"a1", name:"Jim"},
{id:"a2", name:"Zed"},
{id:"a3", name:"Bob"},
];
objects.sort(function(o1,o2){
var n1 = o1.name, n2 = o2.name;
return n1<n2 ? -1 : n1>n2 ? 1 : 0;
});
for (var i=0,len=objects.length; i<len; ++i ){
console.log( objects[i].id );
}
// Result:
// a3, a1, a2
将所有对象保留在哈希中,并单独排序
var objects = {
a1: {id:"a1", name:"Jim"},
a2: {id:"a2", name:"Zed"},
a3: {id:"a3", name:"Bob"},
};
// Easily look up an object by id (can't do this as easily or fast with array)
var id = "a2";
console.log( objects[id] ); // {id:"a2", name:"Zed"}
// Create an array just the ids
var ids = Object.keys(objects);
// Sort the array of ids based on properties of the objects the represent
ids.sort(function(id1,id2){
var n1 = objects[id1].name, n2=objects[id2].name;
return n1<n2 ? -1 : n1>n2 ? 1 : 0;
});
// Iterate the sorted array and use each key to find the object
for (var i=0,len=ids.length; i<len; ++i){
console.log( objects[ids[i]].name );
}
// Result:
// Bob, Jim, Zed
关于javascript - 排序数组会删除条目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9333037/