排序数组删除条目

Sorting array removes entries?

本文关键字:删除 数组 排序      更新时间:2023-09-26

在排序之前,我可以正确地按键访问数组值。

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]

如果您在浏览器中打开开发人员工具,您可以自己看到这一点;所有现代浏览器都有它们;如果需要帮助,请使用谷歌搜索—并在排序后添加代码CCD_ 4。使用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

Java脚本数组以0开头。您的第0个元素现在已排序为最后一个。

请注意,您的示例中没有"多维数组",只有对象数组。