Beertastic
Beertastic

Reputation: 711

Using javascript vars as array key names

I'm making a grid of 18 x 9 and want to calculate the sizes for all possible boxes that could be placed on the grid.

I'm placing them in objects, but the line

var template_sizes_site[x + 'x' + y] = {};

Is failing. it seems I can't use variables AND a string to name key?

I want basically to say array['2x9']['width'] = 42; etc

What am I missing?

var template_sizes = {};
var site_width = 70;
var site_height = 70;
var site_margin = 20;

for (var y = 1; y <= 9; y++)
{ 
for (var x = 1; x <= 18; x++)
    {
        var template_sizes_site[x + 'x' + y] = {};
        template_sizes_site[x + 'x' + y]['width'] = ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0));
        template_sizes_site[x + 'x' + y]['height'] = ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0));
    }
}

Upvotes: 0

Views: 67

Answers (3)

ST3
ST3

Reputation: 8946

You need to change var template_sizes_site[x + 'x' + y] = {}; into template_sizes_site[x + 'x' + y] = {}; because your way creates local variable in scope and after leaving it (when loop goes to next time) data is becomes lost.

Also template_sizes_site is not initialized if it is all your code.

Upvotes: 1

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

Remove the var from your first line in the body of your nested for loop:

var template_sizes = {};
var site_width = 70;
var site_height = 70;
var site_margin = 20;

for (var y = 1; y <= 9; y++)
{ 
    for (var x = 1; x <= 18; x++)
    {   
        template_sizes_site[x + 'x' + y] = {};
        template_sizes_site[x + 'x' + y]['width'] = ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0));
        template_sizes_site[x + 'x' + y]['height'] = ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0));
    }
}

var is only for variables, not for properties:

var template = {}; // OK
var template_sizes_site[x + 'x' + y] = {}; // not allowed, no need

Also you'll need to initialise template_sizes_site if that wasn't a typo.

Upvotes: 3

Sirko
Sirko

Reputation: 74046

You did not initialize your variable template_sizes_site (is this meant to be template_sizes ?). Also you could shorten your initialization code a little like shown below.

var template_sizes = {},
    template_sizes_site = {},
    site_width = 70,
    site_height = 70,
    site_margin = 20;

for (var y = 1; y <= 9; y++) { 
  for (var x = 1; x <= 18; x++) {
        template_sizes_site[x + 'x' + y] = {
           'width': ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0)),
           'height': ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0))
        };
  }
}

Upvotes: 1

Related Questions