Finding all the road construction sites and delete them:?
-
This is what I do, but doesn't seem to work
var thisRoom = Game.spwans["Spawn1"].room; var constructionSites = thisRoom.find(FIND_CONSTRUCTION_SITES); for (var site in constructionSites) { if (site.structureType == STRUCTURE_ROAD) { site.remove(); } }
From my debugging result, looks like site.structureType is undefined.
-
for (var siteName in constructionSites) { let site = Game.constructionSites[siteName]; if (site.structureType == STRUCTURE_ROAD) { site.remove(); } }
-
for (var site of constructionSites) {
constructionSites is an array. If you iterate over an array with "in", you get the index positions of the array (0,1,2 etc). This is analogous to how you get the keys of an object if you iterate over it using in.
If you iterate over an array with "of" you get the contents of the array, and this is what you want here.
-
@wtfrank Thank you! Really need to spend more time on JS
-
Footnote:
for (X of Y)
doesn't work for all kinds of objectsfor (X in Y)
would... So be warned. But it certainly works for simple arraysand objects.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
-
@wtfrank
Game.constructionSites
is not an array. @Orletfor..of
does not work with simple objects.Looping over the collections in the
Game
object (e.g.Game.constructionSites
) either need to usefor..in
or_.forEach
.
-
@deft-code even more so. Thanks for correcting me!
-
@deft-code This is an array though:
var constructionSites = thisRoom.find(FIND_CONSTRUCTION_SITES);
-
@wtfrank Oops. Yeah I lost the context somewhere in there. You're correct. I use
for..of
all the time to loop over the results ofRoom.find