我正在尝试编写一个脚本,从对象列表中随机选择三个项目,按一个字段将它们按字母顺序排列,然后显示另一个字段的字母顺序值。到目前为止,我可以让它随机选择项目并显示它们,但它仍然没有排序。这是我的代码:
function random_text() {};
var random_text = new random_text();
var number = 0;
random_text[number++] = {
show: "Bob",
sort: "A"
}
random_text[number++] = {
show: "Casey",
sort: "B"
}
random_text[number++] = {
show: "Dan",
sort: "C"
}
random_text[number++] = {
show: "Alfred",
sort: "D"
}
var random_number = Math.floor(Math.random() * number);
var random_number1 = Math.floor(Math.random() * number);
var random_number2 = Math.floor(Math.random() * number);
if (random_number !== random_number1) {
var name1 = random_text[random_number1].show;
} else {
var name1 = "";
}
if (random_number !== random_number2 && random_number1 !== random_number2) {
var name2 = random_text[random_number2].show;
} else {
var name2 = "";
}
var name3 = random_text[random_number].show;
var objs = [name1 + " " + name2 + " " + name3];
objs.sort(function (a, b) {
var nameA = a.sort.toLowerCase(),
nameB = b.sort.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB) return 1
return 0 //default return value (no sorting)
})
document.write(objs.sort());
在此先感谢您的帮助。如果有任何方法可以清理代码,我也很感激这方面的提示。