简体   繁体   English

推送后未定义的数组

[英]Undefined array after push

I'm trying to obtain to sort an array of mountain from the tallest to the smallest but when trying to print, I get 我试图获得从最高到最小的山脉排序,但是当尝试打印时,我得到

TypeError: mountainArray[i] is undefined

I think i'm not missing any step for the solution but I get undefined. 我认为我没有错过任何解决方案的步骤,但是我不确定。

Thanks in advance 提前致谢

Code below: 代码如下:

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

The way you have your class written: 您上课的方式:

function Mountain(position, height) {
  this.position = position;
  this.height = height;
}

You need to use the new keyword when you push: 推送时需要使用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);
  }
}

as pointed out in the comments, you should only sort once, no need to do it every time in your loop. 正如评论中指出的那样,您应该只排序一次,而不必在循环中每次都进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM