2013-10-18 28 views
0

我正在制作一个18 x 9的网格,并且想要计算可以放置在网格上的所有可能框的大小。使用javascript变量作为数组键名

我把他们中的对象,但行

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

失败。看来我不能使用变量和一个字符串来命名密钥?

我想基本上说array['2x9']['width'] = 42;

我缺少什么?

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)); 
    } 
} 

回答

3

从第一行中的嵌套的身体中取出var for循环:

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仅供变量,而不是性质:

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

还你”如果那不是拼写错误,你需要初始化template_sizes_site

+0

这工作..! WOOP ... – Beertastic

1

您没有初始化变量template_sizes_site(这是否意味着template_sizes?)。你也可以缩短你的初始化代码,如下所示。

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)) 
     }; 
    } 
} 
1

您需要更改var template_sizes_site[x + 'x' + y] = {};template_sizes_site[x + 'x' + y] = {};因为你的方式创建的范围局部变量和离开它(当循环进入后面的时间)后的数据开始丢失。

另外template_sizes_site如果它是您的所有代码,则不会进行初始化。