const arr = [2133, 435, 34, 234, 655, 345, 112, 4, 432, 6654, 1001];
const output = {
asc_1: [],
asc_2: [],
desc_1: [],
desc_2: []
};
output.asc_1 = arr.sort((a, b) => (a > b ? 1 : 0)); // Sort values low to high
output.desc_1 = arr.sort((a, b) => (a < b ? 1 : 0)); // Sort values high to low
output.asc_2 = arr.sort((a, b) => a - b); // Sort values low to high
output.desc_2 = arr.sort((a, b) => b - a); // Sort values high to low
console.log({ output });
output:
asc_1: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
asc_2: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
desc_1: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
desc_2: (11) [6654, 2133, 1001, 655, 435, 432, 345, 234, 112, 34, 4]
运行此代码时,它们全部将在output
对象中以降序显示,尽管如果我一一运行它们,它们将按预期运行。
此代码有什么问题?
output.asc_1 = [...arr].sort((a, b) => (a > b ? 1 : -1)); // Sort values low to high
output.desc_1 = [...arr].sort((a, b) => (a < b ? 1 : -1)); // Sort values high to low
output.asc_2 = [...arr].sort((a, b) => a - b); // Sort values low to high
output.desc_2 = [...arr].sort((a, b) => b - a); // Sort values high to low