2009. 9. 7. 19:27 컴퓨터이야기/JavaScript



eval 함수를 이용한 가변 변수
 
<script type="text/javascript">
var aux="aux"
s_array=new Array("www.daum.net", "www.naver.com", "www.yahoo.com")

for (j=0; j < s_array.length; j++ ){
  eval("var " + aux + j)
     eval(aux+j + " = s_array[j]");
  document.write(eval(aux + j))
   document.write("<br><br>")
}

</script>

-----------------------결 과 -----------------------------------
www.daum.net

www.naver.com

www.yahoo.com
------------------------------------------------------------------


<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>

<SCRIPT LANGUAGE="JavaScript">
<!--
function val(){
 for(i=0;i<3;i++){
  var aux="aux"
  alert("document.siteform."+aux+i+".value") // 결과 document.siteform.aux0.value | document.siteform.aux1.value | document.siteform.aux2.value
 }
}
function reper(){
 for(i=0;i<3;i++){
  var aux="aux"
   alert(eval("document.siteform."+aux+i+".value")) // 결과 www.daum.net | www.navy.net | www.asdf.net
 }
}
//-->
</SCRIPT>

 </HEAD>

 <BODY>
  <FORM name="siteform" METHOD=POST ACTION="">
 <input type="hidden" name="aux0" value="www.daum.net">
 <input type="hidden" name="aux1" value="www.navy.net">
 <input type="hidden" name="aux2" value="www.asdf.net">
 <input type="button" name="변수로" value="변수로" onclick="val()">
 <input type="button" name="값로" value="값로" onclick="reper()">
  </FORM>
 </BODY>
</HTML>
----------------------------결과 -------------------------------------------------------------
val() 함수 호출시
document.siteform.aux0.value | document.siteform.aux1.value | document.siteform.aux2.value

reper() 함수 호출시
결과 www.daum.net | www.navy.net | www.asdf.net

---------------------------------------------------------------------------------------------


posted by 변화지시자

댓글을 달아 주세요