我正在尝试对此数组进行排序,但是它对我不起作用。我一定是在做些愚蠢的事情,请问有人看我怎么了吗?
var fruits = [{
config: {
priority: 99
}
}, {
config: {
priority: 1
}
}, {
config: {
priority: 10
}
}];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);
function myFunction() {
let l = fruits.sort(sort);
document.getElementById("demo").innerHTML = JSON.stringify(l);
}
function sort(item1, item2) {
return item1.config.priority < item2.config.priority;
}
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
答案 0 :(得分:1)
应该从sort()
回调中返回一个整数。从第二个减去第一个值
var fruits = [{
config: {
priority: 99
}
}, {
config: {
priority: 1
}
}, {
config: {
priority: 10
}
}];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);
function myFunction() {
let l = fruits.sort(sort);
document.getElementById("demo").innerHTML = JSON.stringify(l);
}
function sort(item1, item2) {
return item2.config.priority - item1.config.priority;
}
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
答案 1 :(得分:1)
使用-不是<< / p>
const fruits = [{ config: { priority: 99 } }, { config: { priority: 1 } }, { config: { priority: 10 } }];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);
function myFunction() {
let l = fruits.sort(sort);
document.getElementById("demo").innerHTML = JSON.stringify(l);
}
function sort({ config: { priority: p1 }}, { config: { priority: p2} }) {
return parseInt(p1) - parseInt(p2);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>