我正在制作一个18 x 9的网格,并希望计算可放置在网格上的所有可能框的大小。
我将它们放在对象中,但是行
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));
}
}
答案 0 :(得分:3)
从嵌套for循环体中的第一行中删除var
:
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
。
答案 1 :(得分: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))
};
}
}
答案 2 :(得分:1)
您需要将var template_sizes_site[x + 'x' + y] = {};
更改为template_sizes_site[x + 'x' + y] = {};
,因为您的方式会在范围内创建局部变量,并在离开后(当循环进入下一次时)数据将丢失。
如果它是您的全部代码,则template_sizes_site
也未初始化。