【问题标题】:JavaScript sorting array by nameJavaScript 按名称排序数组
【发布时间】: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;
}

【问题讨论】:

  • customerNamemonthlyChargepastDueAmountnumDaysPastDue 是单独的数组吗?您每次都必须构建一个对象数组吗?还是你已经有一个对象数组?

标签: javascript sorting


【解决方案1】:

您的问题在于填充表格的代码。您总是引用同一个记录对象并每次都更改其值。这就是为什么所有记录似乎都具有您上次输入的值的原因。应该是这样的:

for (let i = 0; i < 10; i++)
    {
        // you need to instantiate a new record if it's a class or simply create a new object
        record = {}
        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;

【讨论】:

  • 或者使用对象字面量语法和var 来确保正确的作用域:var record = { Customer: customerName[i], MonthlyCharge: monthlyCharge[i], PastDueAmount: pastDueAmount[i], DaysPastDue: numDaysPastDue[i] }; 在任何情况下你都应该使用var(或者const在更新的浏览器中)......跨度>
  • 感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2018-11-02
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
  • 2021-11-03
相关资源
最近更新 更多