2013-10-18 31 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如果它是您的所有代碼,則不會進行初始化。