How to iterate structures properly

921 views Asked by At

I'd like to iterate found structures but I don't know what way is the best for this.

I've tried this one:

for (var ext in creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }})){
    console.log(ext.energy);
}

but it doesn't work.

So for now I'm using an approach that works, but it looks ugly:

for(var i = 0; i < creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }}).length; i++) {
    var ext = creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }})[i];
    console.log(ext.energy);
}

I'm not sure, maybe this is a question related to js. I'm a completely newbie in js. Can you advice about this?

2

There are 2 answers

2
avdg On BEST ANSWER

ext contains the key, not the value of the result.

So what I have done, is move the results out of the loop and put in a variable called results. That way, I have a variable to reference to in the loop.

So whats going on is that, because the ext in your code is storing the key, which is a string type value. Its returning the results from the string object, you're doing something like "key".energy and that returns the value undefined, because the String object doesn't have a key like that.

So here below is the code that should work:

var results = creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }});
for (var ext in results){
    console.log(results[ext].energy);
}
0
dragn On

Don't forget that you can also use Array.forEach function and arrow functions notation!

creep.room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_EXTENSION } })
    .forEach((ext) => { console.log(ext.energy); });