Code question (Javascript): getting properties of objects in arrays

Lang: Javascript - Board: Gold Rush

I understand programming logic, but I’m lost when comes to language specifics. I’m trying to loop through the 1st 5 objects in the array and pick the one with the biggest bountyGold.


var items = this.getItems();  //create array of items
var itemValue = 0;

// find best of closest 5
for(var i = 0; i < 4; ++i) {
    var item = items[i];
    if (item.bountyGold > itemValue) { //if it's better, use it| BTW this is line 7
        itemValue = item.bountyGold;
        var itemPos = item.pos;

// Strip coordinates
itemX = itemPos.x;
itemY = itemPos.y;

I keep getting an error at line 7 saying that “item” is null.

I have no idea what is wrong with my code, but I’m sure it’s something stupid. Any help would be appreciated.

Thanks in advance,


you should ask you the question : What happened if there is not 5 items around ?

My advice : replace 5 by the number of items (sorry, I can’t remember how to do that, maybe items.size).

And I’m not sure that the 5 first items of the array are the closest…
So you should first find the closest 5. Maybe a little more tricky.

Good comment. I assumed that it would carry over but obviously it doesn’t.

I set it all behind an “if (item)” and that works but seems awkward.

What you’re looking for is “arrayName.length” or something similar.

You are right about them not being the closest, but I’m new to Javascript so I’m doing it inch by inch and fine tuning.

Thanks for the help.

Yes .length is correct.