我试图获得从最高到最小的山峰排序,但在尝试打印时,我得到了
TypeError: mountainArray[i] is undefined
我认为我没有错过解决方案的任何步骤,但我未定义。
提前致谢
以下代码:
var position;
var height;
function Mountain(position, height) {
this.position = position;
this.height = height;
}
function sortMountain(a, b) {
return b.height - a.height;
}
var mountainArray = [];
// game loop
while (true) {
for (var i = 0; i < 8; i++) {
var mountainH = parseInt(readline()); // represents the height of one mountain, from 9 to 0.
mountainArray.push(Mountain(i, mountainH));
mountainArray.sort(sortMountain);
}
for (var i = 0; i < 8; i++) {
print(mountainArray[i].position);
}
}
&#13;
答案 0 :(得分:2)
你上课的方式:
function Mountain(position, height) {
this.position = position;
this.height = height;
}
推送时需要使用new
关键字:
while (true) {
for (var i = 0; i < 8; i++) {
var mountainH = parseInt(readline()); // represents the height of one mountain, from 9 to 0.
mountainArray.push(new Mountain(i, mountainH)); // HERE
mountainArray.sort(sortMountain);
}
for (var i = 0; i < 8; i++) {
print(mountainArray[i].position);
}
}
正如评论中所指出的那样,你应该只排序一次,不需要每次循环都这样做。