我需要对我的数组进行排序,但由于我有两个对象,我不知道该怎么做。我需要按字母顺序和玩具编号按升序对狗名称进行排序。我怎样才能做到这一点?
function start() {
document.getElementById("task").innerHTML="Task 8";
var arr = [];
var vName = "";
vName = prompt("Enter dog name (leave blank to stop)");
vToyNum = prompt("Enter number of dog toys (leave blank to stop)");
while (vName.length > 0 && vToyNum.length > 0) {
arr.push({name:vName,toynum:vToyNum});
arr.sort({name:vName});
vName = prompt("Enter dog name (leave blank to stop)");
vToyNum = prompt("Enter number of dog toys (leave blank to stop)");
}
var vOutput = "Dog names and No. of toys:" + displayDog(arr);
var toyTot = 0;
for (var val=0; val < arr.length; val++) {
toyTot += Number (arr[val].toynum);
}
vOutput += "<br/><br/>Total number of toys: " + toyTot;
document.getElementById("output").innerHTML= vOutput;
}
function displayDog(arr) {
var vOutput = "";
for (var val = 0; val < arr.length; val++) {
vOutput += "<br/> Dog " + (val + 1) +" "+ arr[val].name
+ ", No. of toys " + arr[val].toynum;
}
return vOutput;
}
答案 0 :(得分:0)
您可以使用Array#sort
所需的排序功能进行自定义排序,然后按name
排序,然后按toynum
排序
arr.sort(function (a, b) {
return a.name.localeCompare(b.name) || a.toynum - b.toynum;
});
在使用数据填充数组后,您只需要排序一次。
function start() {
document.getElementById("task").innerHTML = "Task 8";
var arr = [],
vName = "",
vToyNum,
vOutput,
toyTot = 0,
val,
DOG_QUESTION = "Enter dog name (leave blank to stop)",
TOY_QUESTION = "Enter number of dog toys (leave blank to stop)";
vName = prompt(DOG_QUESTION);
vToyNum = prompt(TOY_QUESTION);
while (vName.length > 0 && vToyNum.length > 0) {
arr.push({ name: vName, toynum: vToyNum });
vName = prompt(DOG_QUESTION);
vToyNum = prompt(TOY_QUESTION);
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name) || a.toynum - b.toynum;
});
vOutput = "Dog names and No. of toys:" + displayDog(arr);
for (val = 0; val < arr.length; val++) {
toyTot += Number(arr[val].toynum);
}
vOutput += "<br /><br />Total number of toys: " + toyTot;
document.getElementById("output").innerHTML = vOutput;
}
function displayDog(arr) {
var val, vOutput = "";
for (val = 0; val < arr.length; val++) {
vOutput += "<br /> Dog " + (val + 1) + " " + arr[val].name + ", No. of toys " + arr[val].toynum;
}
return vOutput;
}
start();
<div id="task"></div>
<div id="output"></div>