[英]Sort method for an objects property that is inside an array of objects from a class
我需要地址簿 class 中的 sort() 方法的帮助。 我试图从 stackoverflow 上的示例中自己弄清楚,但我似乎无法让它工作,因为大多数示例不涉及从 class 实例工作。 如果可以,请查看 sort() 方法并让我知道我哪里出错了。 我想我需要以某种方式循环然后重新定位数组顺序。
window.onload = init;
let abm;
function init() {
abm = new AddressBook();
}
class Contact {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
//DO NOT MODIFY ABOVE THIS LINE
function formSubmitted() {
event.preventDefault();
var user = document.getElementById("name").value;
var mail = document.getElementById("email").value;
var newContact = new Contact(user, mail);
abm.add(newContact);
abm.display();
}
function sortList() {
//CODE HERE ONLY
abm.sort();
abm.display();
}
class AddressBook {
constructor() {
this.contactList = [];
}
add(contact) {
//CODE HERE ONLY
this.contactList.push(contact);
}
display(htmlId) {
//CODE HERE ONLY
var html = "<table border='1|1'>";
for (var i = 0; i < this.contactList.length; i++){
html+="<tr>";
html+="<td>"+this.contactList[i].name+"</td>";
html+="<td>"+this.contactList[i].email+"</td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("contacts").innerHTML = html;
}
sort() {
//CODE HERE ONLY
for (var i = 0; i < this.contactList.length; i++){
var tA = this.contactList[i].name.toUpperCase();
var tB = this.contactList[i].name.toUpperCase();
if (tA < tB) {
return -1;
}
if (tA > tB) {
return 1;
}
return 0;
}
}
}
this.contactList.sort((a, b) => a.name.toUpperCase() - b.name.toUpperCase());
您可以在Mozilla 开发人员处了解更多信息
我假设您想对this.contactList
进行就地排序。
请注意,您没有在sort()
代码中对this.contactList
执行任何分配。 这是第一个错误。
第二个错误是您立即从 function 返回一个值,而不是对数据进行排序。
第三个错误是,您无法按O(N)
复杂度进行排序(即单次传递数据)。
您需要决定要实现哪种排序算法,或者使用本机 javascript 实现,即MergeSort
。
在这种情况下,您需要传递一个 function 来表达您想要对数据进行排序的方式和使用哪些属性,这就是您尝试做的,使用 -1、1 和 0。
在这种情况下,您可以通过以下方式实现sort()
:
sort() {
this.contactList = this.contactList.sort(function(a, b) {
var tA = this.contactList[i].name.toUpperCase();
var tB = this.contactList[i].name.toUpperCase();
if (tA < tB) {
return -1;
}
else if (tA > tB) {
return 1;
}
return 0;
}
}
或者以等效的方式(确保您理解它为什么是等效的):
sort() {
this.contactList = this.contactList.sort(function(a, b) {
return a.name.toUpperCase() - b.name.toUpperCase();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.