我正在尝试优化一个函数,该函数将根据用户偏好对多维数组进行排序。 (ID、名称、时间戳等)。 我不想创建许多不同的功能,而是想将它们全部组合成一个。例如,请参阅下面的代码。我不想创建两个不同的函数,而是希望能够将名称或 timeCreated 字符串传递给它,但我不知道如何将字符串转换为点表示法。
compareName (a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
},
compareCreated (a, b) {
if (a.timeCreated < b.timeCreated) {
return -1;
}
if (a.timeCreated > b.timeCreated) {
return 1;
}
return 0;
}
因为某些值可能为空,我发现这个函数比上面的代码能更好地处理事情...我只需要找到一种方法将数组选择器传递给 a 和 b。
alphabetically(ascending) {
return function (a, b) {
// equal items sort equally
if (a === b) {
return 0;
}
// nulls sort after anything else
else if (a === null) {
return 1;
}
else if (b === null) {
return -1;
}
// otherwise, if we're ascending, lowest sorts first
else if (ascending) {
return a < b ? -1 : 1;
}
// if descending, highest sorts first
else {
return a < b ? 1 : -1;
}
};
}
最佳答案
您可以使用[] 表示法
并在函数中接受一个额外参数
alphabetically(ascending) {
return function (a, b, prop) {
// equal items sort equally
if (a[prop] === b[prop]) {
return 0;
}
// nulls sort after anything else
else if (a[prop] === null) {
return 1;
}
else if (b[prop] === null) {
return -1;
}
// otherwise, if we're ascending, lowest sorts first
else if (ascending) {
return a[prop] < b[prop] ? -1 : 1;
}
// if descending, highest sorts first
else {
return a[prop] < b[prop] ? 1 : -1;
}
};
}
关于javascript - 如何将字符串转换为数组选择器的点表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826959/