【发布时间】:2020-11-04 01:08:18
【问题描述】:
我正在对包含对象的数组进行排序。我正在根据字母顺序对姓氏进行排序。 但是当我打印出来时,只有排序数组的第一项出现并且它填充了数组。 意思是数组 =[{name: "White, David", score:100},{name: "Bee, Axis", score:101}] 按姓氏排序后数组变成array =[{name: "Bee, Axis", score:101},{name: "Bee, Axis", score:101}],所有信息都是一样的。不知道怎么回事?
这里是填充数组:
for (let i = 0; i < 10; i++)
{
record.Customer= customerName[i];
record.MonthlyCharge = monthlyCharge[i];
record.PastDueAmount = pastDueAmount[i];
record.DaysPastDue = numDaysPastDue[i];
records.push(record);
table += `<tr>`;
table +=`<td>${record.Customer}</td>`;
table +=`<td>$${record.MonthlyCharge}</td>`;
table +=`<td>$${record.PastDueAmount}</td>`;
table +=`<td>${record.DaysPastDue}</td>`;
table +=`</tr>`;
}
tableBody.innerHTML = table;
对数组进行排序
nameColumn.addEventListener("click", function (){
records.sort((a,b)=>a.Customer.localeCompare(b.Customer));
updateTable();
});
function updateTable()
{
let table = "";
for (let record of records)
{
table += `<tr>`;
table +=`<td>${record.Customer}</td>`;
table +=`<td>$${record.MonthlyCharge}</td>`;
table +=`<td>$${record.PastDueAmount}</td>`;
table +=`<td>${record.DaysPastDue}</td>`;
table +=`</tr>`;
}
tableBody.innerHTML = table;
}
【问题讨论】:
-
customerName、monthlyCharge、pastDueAmount和numDaysPastDue是单独的数组吗?您每次都必须构建一个对象数组吗?还是你已经有一个对象数组?
标签: javascript sorting