This is something that has been bugging me for a while now. In Typescript if I define a For-in loop my variable is always treated as a string. Example:
for(var room in this.rooms) {
room.placement.x = 52;
}
The "room.placement.x" will fail because it treats "room" as a string. "this.rooms" is actually a collection of Room objects, but room is not a Room... it's a string.
Is this a Typescript version issue or something that is sticking around. It's highly frustrating.
Is there a way to define room so that Typescript can treat it like a Room?
The definition of rooms is: "private rooms: Room.Game.Room[];"
It's an array of a custom object.
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object.
To iterate over a string with index: Use the spread syntax (...) to unpack the string into an array. Use the forEach() method to iterate over the array. The second parameter the forEach() method takes is the index of the current element.
In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. When a for loop executes, the following occurs: The initializing expression initialExpression , if any, is executed.
If this.rooms
is an array, the proper syntax is for ...of
for (let room of this.rooms) {
room.placement.x = 52;
}
for ... in
iterates over the keys
see this for more
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With