<script type="text/javascript">
function test(){
 array=[];
id=parseInt(document.getElementById('txt_one').value);
k=0;
alert("id是"+id);
switch(k){
 case 0:
 array[id]=id;
 break;
}
for(var i=0;i<array.length;i++){
alert("数组的长度为"+array.length);
alert(array[i]);
}
}
</script>
  
  <body>
   <input type="text" id="txt_one" value="0"/>
   <input type="button" id="btn_one" value="点击" onclick="test()"/> 
  </body>
</html>怎么就让数组把id为不同的值都存储呢? 如果id为1的话 array[0]的值一直为undefined ,我想id为1的时候,array[0]=0,array[1]=1,怎么实现呢

解决方案 »

  1.   

    看这代码LZ的js基础有点差啊。。<!doctype html>
    <html>  
        <head>  
            <title>Test page</title>  
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        </head>  
        <body>
    <input type="text" id="txt_one" value="0"/>
    <input type="button" id="btn_one" value="点击" onclick="test()"/>  
    <script type="text/javascript">
    function test(){
    var arr = [],
    val = parseInt(document.getElementById('txt_one').value);
    for(var i = 0; i <= val; i++){
    arr[i] = i;
    }
    alert(arr);
    }
    </script>
        </body>  
    </html>  
      

  2.   

    switch(k){
      case 0:
      array[id]=id;
      break;
    }
    你这个地方已经限制了array
      

  3.   

    不是要这种 就是要switch的这种,楼上的这种写法我懂的,帮帮我额 谢了
      

  4.   

    <html>
    <head>
    <script type="text/javascript">
    function test(){
      array = [];
    id = parseInt(document.getElementById('txt_one').value);
    for(var i = 0; i <= id; i++)
    {
    array[i] = i;
    }
    alert("数组的长度为" + array.length);
    for(var i = 0; i < array.length; i++)
    {
    alert("第" + (i+1) + "位:" + array[i]);
    }
    }
    </script>
    </head>
    <body>
    <input type="text" id="txt_one" value="0"/>
    <input type="button" id="btn_one" value="点击" onclick="test()"/> 
    </body>
    </html>
    不知是不是要这样的啊?
      

  5.   

    如果是必须用switch的话,那么你知道究竟要写多少个case
      

  6.   


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var array = [];//变量问题你把它在函数外面定义就行了
            function test() {
                
                id = parseInt(document.getElementById('txt_one').value);
                k = 0;
                alert("id是" + id);
                switch (k) {
                    case 0:
                        array[id] = id;
                        break;
                }
                for (var i = 0; i < array.length; i++) {
                    alert("数组的长度为" + array.length);
                    alert(array[i]);
                }
            }
    </script>
     
     
    </head>
    <body>
    <input type="text" id="txt_one" value="0"/>
       <input type="button" id="btn_one" value="点击" onclick="test()"/>  </body>
    </html>
      

  7.   

    哦,嗯,是这个问题,对,我应该设成全局变量,我以为不加VAR 就是全局变量呢