-1

I'm trying to translate a "shape" (set of relative coordinates for four squares) to a pixel grid:

var grid_center = 6;
var square_size = 20;

l_shape = {
    coords: [[-1, 0], [0, 0], [1, 0], [-1, 1]]
}

function draw_shape(shape, grid_location) {
    for (coord in shape.coords) {
        trans_coord = (grid_location[0] + coord[0]) * square_size;
        console.log(trans_coord);
    }
}

draw_shape(l_shape, [grid_center - 1, 0]);

Expected output:

100
120
140
160

Actual output:

1000
1020
1040
1060

Looks like it could be automatic type conversion weirdness, but I don't see how. All of my numbers are actual numbers, none quoted as strings. When entering the math manually, I get the expected result:

> (5 + 0) * 20
100

There may be better ways to do this from a computer science perspective, but I'm not interested in those. I just want to find out why the program above doesn't work as intended.

tadman
  • 208,517
  • 23
  • 234
  • 262
eil
  • 113
  • 1
  • 6

3 Answers3

1

for (coord in shape.coords) will assign index string to coord

You want for (coord of shape.coords)

Mike Rapadas
  • 4,613
  • 2
  • 28
  • 21
0

for (coord in shape.coords) will return the property indexer. You need to use shape.coords[coord] to access the actual number value.

Or you can also use forEach

e.g.

var grid_center = 6;
var square_size = 20;

l_shape = {
  coords: [
    [-1, 0],
    [0, 0],
    [1, 0],
    [-1, 1]
  ]
}

function draw_shape(shape, grid_location) {
  for (coord in shape.coords) {
    trans_coord = (grid_location[0] + shape.coords[coord][0]) * square_size;
    console.log(trans_coord);
  }

  // or
  shape.coords.forEach(function(coord) {
    trans_coord = (grid_location[0] + coord[0]) * square_size;
    console.log(trans_coord);
  });
}

draw_shape(l_shape, [grid_center - 1, 0]);
H77
  • 5,859
  • 2
  • 26
  • 39
-1

The way you're iterating here is a little off. You're using the for ... in method which is specifically for:

The for...in statement iterates over the enumerable properties of an object...

If you look at the values of coord you're getting they're '0', '1' and so on. This is because in JavaScript an array is object enough for that for to work on it, but that's not what you wanted.

What you want is the array iterator forEach. The code looks like this if you're using ES6:

var grid_center = 6;
var square_size = 20;

var l_shape = {
    coords: [[-1, 0], [0, 0], [1, 0], [-1, 1]]
}

function draw_shape(shape, grid_location) {
  shape.coords.forEach(coord => {
    trans_coord = (grid_location[0] + coord[0]) * square_size;
    console.log(trans_coord);
  })
}

draw_shape(l_shape, [grid_center - 1, 0]);

The results aren't what you expect, but you're on the right track now.

tadman
  • 208,517
  • 23
  • 234
  • 262