Search code examples
javascriptjavascript-objectsfor-in-loop

Can't assign values to properties of object with a "for...in" loop


Here's my object:

var cornersAbs = {
    topLeftCorner: { x: center.x + orin.corners.topLeft.x, y: center.y + orin.corners.topLeft.y, OOB: false },
    topRightCorner: { x: center.x + orin.corners.topRight.x, y: center.y + orin.corners.topRight.y, OOB: false },
    bottomLeftCorner: { x: center.x + orin.corners.bottomLeft.x, y: center.y + orin.corners.bottomLeft.y, OOB: false },
    bottomRightCorner:{ x: center.x + orin.corners.bottomRight.x, y: center.y + orin.corners.bottomRight.y, OOB: false }
}

And my loop

for (var corner in cornersAbs) {
    corner.OOB = corner.x < 0 | corner.y < 0 | corner.x > canvas.width | corner.y > canvas.height;
}

doesn't seem to be assigning any values to the corner.OOB properties.

Nothing seems to help, even if I write the loop like so:

for (var corner in cornersAbs) {
    cornersAbs.corner.OOB = cornersAbs.corner.x < 0 | cornersAbs.corner.y < 0 | cornersAbs.corner.x > canvas.width | cornersAbs.corner.y > canvas.height;
}

(I tried writing it this way because console.log(corner) for each iteration would print "topLeftCorner", "topRightCorner", etc. instead of "cornersAbs.topLeftCorner," etc. Writing the loop this way, however, gives me an error saying that cornersAbs.corner is undefined.)

Using bracket notation doesn't help either.

When I print the value of any corner.OOB the console prints "false" (the value I initalize each corner.OOB to) or "undefined."

I've tested the positions I'm reading into corner.x and corner.y, they are working fine.


Solution

  • You want to do:

    cornersAbs[corner]=...
    

    to access the 'corner' you are looking at.

    To see a sub-property, you use cornerAbs[corner].prop, which indexes the property referred to by corners and looks at prop within it.

    On the other hand, cornerAbs.corner is equivalent to cornerAbs["corner"], which is not what you want.