Problem with .pos on Gold Rush

I was having a problem with my code:

var items = this.getItems();
var currentShortOfArray = 1;
for(var i=0;i-1<items.length;++i){
    var iPos = items[i];
    var iClose = this.distance(iPos.pos);
    var curClose = this.distance(items[currentShortOfArray].pos);
     currentShortOfArray = i;

When I press Run, I get an error that says:

Line 16, time 0.0: Cannot read property ‘pos’ of undefined

Does anyone by chance know what I’m doing wrong?

I am using JavaScript. Forgot to mention that.

I think I see the problem. Your for-loop will iterate past the end of the array because of the i-1 you have. Try just using i with no -1 there. So if items.length is, say, 3, then you will want to access indices 0, 1, and 2, but not 3 (because there’s nothing in index 3–that would be the fourth element).

What are you trying to do with the currentShortOfArray variable, by the way?

Ok. the currentShortOfArray tells the program which of the objects on the array is the closest. It just holds the number of it. Thanks!

Oh, I forgot to include this in the code. The above mention variable is used for this line of code I left out:
Now this is the only problem I have. Its same as before. Sorry, I forgot :frowning:

You should check out what’s happening to currentShortOfArray, then. You set it to 1 in the beginning, but there may not be two items in the array. You should initialize it to, say, -1, and then only move if you found something:

if (currentShortOfArray !== -1)

@nick Thanks. I’ll try that. Thanks again.

Same error on the this.move(items[currentShortOfArray].pos);
I checked the variables, and all the ones in the for loop are undefined.
currentShortOfArray is some how -1, even though thats not in the code…

@nick YES IT WORKS THANK YOU NICK!!! I changed curClose into two lines like the iPos and iClose, and changed the line var currentShortOfArray = 1; to var currentShortOfArray = 0;. Programming… It perplexes the mind, and the logical system… … . . …

I just have one last question… how would you find the gold amount of the other player?


Thank you! That helps