1. 程式人生 > >動態建立2維陣列Array (例子原始碼)

動態建立2維陣列Array (例子原始碼)

<html>
 <head>
 </head>
 
 <script type="text/javascript">
  // Storing the list display value
  var listArray;
  
  /**
   * Store the input value to listArray
   * with identified by name.
   */
  function setListArray(sName, sValue){
   alert(sValue);
   // listArray is null
   if (listArray == null){
    // Initialize the listArray
    listArray = new Array();
    // Store the first group
    listArray[0] = new Array(sName, sValue);
   }
   // listArray is not null
   else{
    // declare flag
    var valueFound = false;
    for (var i = 0; i < listArray.length; i ++){
     // find in the old array
     if (listArray[i][0] == sName){
      // store the value
      listArray[i][listArray[i].length] = sValue;
      // set flag when matched
      valueFound = true;
      // Exit for looping when matched
      break;
     }
    }
    //alert(listArray[0].length);
    // new a group when not matched
    if (!valueFound){
     //var index = listArray.length;
     listArray[listArray] = new Array(sName, sValue);
    }
   }
   //alert(listArray[0].length);
  }
  
  /**
   * get the value from listArray with name and index
   */
  function getListArray(name, index){
   if (index == 0){
    return "";
   }
   // return false when listArray is null;
   if (listArray == null){
    alert("No listArray found!");
    return false;
   }
   // Loop the listArray to found the object.
   for (var i = 0; i < listArray.length; i ++){
    if (listArray[i][0] == name){
     // display the value
     return listArray[i][index];
    }
   }
   alert("No record could be found in listArray");
  }
  
  /**
   * Set the value to the special Element
   */
  function selectChanged(name, index, targetObj){
   // get the target element
   var obj = document.getElementById(targetObj);
   // return false when target element cannot be found.
   if (obj == null){
    alert("Element '" + targetObj + "' cannot be found!");
    return false;
   }
   obj.value = getListArray(name, index);
  }
 </script>
 <body>
  <table>
   <tr>
    <td>
     <select name="sel" onchange="selectChanged('sel', this.selectedIndex, 'show')">
      <option value="00">(none)</option>
      <option value="01">name 01</option>
      <option value="02">name 02</option>
      <option value="03">name 03</option>
      <option value="04">name 04</option>
     </select>
    </td>
    <td>
     <input type="text" name="show" value=""/>
    </td>
   </tr>
   <tr>
    <td colspan="2"><input type="button" value="disply"/></td>
   </tr>
  </table>
 </body>
</html>
<script type="text/javascript">
 setListArray('sel', 'name 01');
 setListArray('sel', 'name 02');
 setListArray('sel', 'name 03');
 setListArray('sel', 'name 04');
</script>