2013-10-18 2 views
0

나는 18 x 9 격자를 만들고 격자에 배치 할 수있는 모든 가능한 상자의 크기를 계산하려고합니다. 나는 객체에 배치 합니다만, 라인배열 키 이름으로 javascript vars 사용

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을 제거

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

당신은 template_sizes_site[x + 'x' + y] = {};var template_sizes_site[x + 'x' + y] = {};을 변경해야하고 (루프가 다음 번에 갈 때)을 떠난 후 데이터가 손실이된다.

template_sizes_site 또한 코드가 모두있는 경우 초기화되지 않습니다.

관련 문제