2014-06-15 4 views
0

뭔가 이것에 대해 옳지 않은 것처럼 보일 때마다 의도 한대로 작동을 멈추고 나서 뭔가 빠졌습니다.다차원, 매트릭스 배열 구성

/*this is a test of a nameing system */ 

var name = ""; /* <-- if you put a name here it will be used instead of a the list of names*/ 

names = [ /*female names*/ ["ann", "chi", "sue", "sally", "tammy", "wowser"], /*male names*/ ["joe", "don", "bob"]]; 

var myname = ""; /*<-- multipurpose filler for later use also*/ 
var i = 0; /* <-- pre establised varible to stop out of scope errors */ 
var sex = 0; /* <-- put here to represent varible provided else where not included here*/ 

if (name !== "") { 
    myname = name; 
} else { 
    if (sex === 0) { 
     for (n = 0; n < names[0].length; n++) { /*<-- my solution to how large an array is*/ 
      if (names.length < 0) { 
       break; 
      } 
     } 
     i = Math.floor((Math.random() * (n - 1 + 1)) + 1) - 1; /* my solution to not being able to randomly generate zero*/ 
     myname = names[sex][i]; 
    } else { 
     for (n = 0; n < names[0].length; n++) { /*<-- my solution to how large an array is*/ 
      if (names.length < 0) { 
       break; 
      } 
     } 
     i = Math.floor((Math.random() * (n - 1 + 1)) + 1) - 1; /* my solution to not being able to randomly generate zero*/ 
     myname = names[sex][i]; 
    } 
} 
alert(myname); 

어떤 지침도 인정 될 것입니다. (나는 Ctrl 키를 눌렀지만 올바르게 포맷 된 것 같지 않습니다.) 게시 후 자체적으로 수정되었습니다.

답변

0

names[0]은 배열이므로 names[0].length으로 길이를 확인할 수 있습니다. names[1]에 대해서도 마찬가지입니다. 따라서 sex이 0 또는 1이라고 가정하면 :

if (name) { 
    myname = name; 
} else { 
    myname = names[sex][Math.floor(Math.random() * names[sex].length)]; 
}