我是JavaScript新手。我目前在功能obj。我有這樣的代碼:用JavaScript排序對象數組後,我將如何顯示相反的排序方式? (更新)
var tableIn = [
{name: "Alaska Thunderfuck", itemsBought: 15},
{name: "Courtney Act", itemsBought: 20},
{name: "Bianca del Rio", itemsBought: 13}
];
//going to use loops to limit input to specific words
var question1= prompt("By what to sort? type in : name or items bought").toLowerCase();
var question2= prompt("How to sort? up/down:").toLowerCase();
function myFunction(question1, question2) {
tableIn.sort(function sortingA(x,y) {
if (question2 == "up") {
if (question1 == "name") {
var ayy = x.name.toLowerCase();
var byy = y.name.toLowerCase();
if (ayy < byy) {return -1;}
if (ayy > byy) {return 1;}
return 0;
} else {
return x.itemsBought - y.itemsBought;
}
}
});
tableIn.sort(function sortingD(x,y) {
if (question2 == "down") {
return -1 * sortingA(x,y);
}
});
for (var idx = 0; idx < tableIn.length; idx++) {
console.log(tableIn[idx].name + tableIn[idx].itemsBought);
}
}
myFunction(question1, question2);
我怎樣才能獲得的第二部分工作?它的反向選項
呀!你可以一直運行一個反向循環。爲'(var idx = tableIn.length - 1; idx> = 0; idx - )'。儘管你可以將它排在第一位。 –