gpt4 book ai didi

javascript - 推送后未定义的数组

转载 作者:行者123 更新时间:2023-11-30 16:03:22 25 4
gpt4 key购买 nike

我正在尝试从最高到最小对一组山进行排序,但是在尝试打印时,我得到了

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);
}
}

最佳答案

您编写类(class)的方式:

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);
}
}

正如评论中所指出的,您应该只排序一次,而不需要在循环中每次都这样做。

关于javascript - 推送后未定义的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37377508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com