javascript 排序数组对象[已关闭]

np8igboo  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(428)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
8小时前关闭
Improve this question
作为一个绝对的javascript初学者,我目前正在一个todo应用程序上练习。应通过单击列标题,按标题、日期、状态和优先级对条目进行排序。附件是我的尝试,但我似乎做错了什么。有人能帮我吗?

const todos = [
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 1", description: "first try", prio: 1, state: "done"}
];

const titleSort = document.getElementById("sort-title");

function sortTitle(a, b) {
  // alert("Titel sortieren");

  const titleA = a.title.toUpperCase();
  const titleB = b.title.toUpperCase();

  let comparison = 0;
  if (titleA > titleB) {
    comparison = 1;
  } else if (titleA < titleB) {
    comparison = -1;
  }
  return comparison;
}

titleSort.addEventListener("click", sortTitle);
cl25kdpy

cl25kdpy1#

事件侦听器将把event对象传递给sortTitle函数…不是todos数组。你的回归将无处可去。
所以...对于事件侦听器,您必须传递一个要执行的函数。在该函数中,指定要排序的数组以及返回数组的位置。

const todos = [
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 2", description: "second try", prio: 1, state: "done"},
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 3", description: "third try", prio: 1, state: "done"},
  {id: 1, duedate: "2023-06-30", title: "Javascript Project 1", description: "first try", prio: 1, state: "done"}
];

const titleSort = document.getElementById("sort-title");

function sortTitle(array) {
  
  return array.sort((a,b) => {

    const titleA = a.title.toUpperCase();
    const titleB = b.title.toUpperCase();

    let comparison = 0;
    if (titleA > titleB) {
      comparison = 1;
    } else if (titleA < titleB) {
      comparison = -1;
    }
    return comparison;
  })
}

// I don't know where you want to return the sorted array... So I just console logged it.
titleSort.addEventListener("click", () => console.log(sortTitle(todos)));
.as-console-wrapper{
  max-height: 100% !important;
}
<button id='sort-title'>Sort me</button>

相关问题