JavaScript Tutorial/Array/String Indexer

Материал из Web эксперт
Перейти к: навигация, поиск

Array String Indexes

It is possible to index arrays using strings.

To access an element, a string index value is placed into the [] operator.



<HTML>
<SCRIPT LANGUAGE="JavaScript">
<!--
    function populateArray(myArray) {
      myArray["A"]=4;
      myArray["B"]=2;
      myArray["C"]=1;
      myArray["D"]=5;
    }
    function displayArray(myArray){
      document.write(myArray["A"]," A.<BR>");
      document.write(myArray["B"]," B.<BR>");
      document.write(myArray["C"]," C.<BR>");
      document.write(myArray["D"]," pairs of D.");
    }
    var myArray = new Array();
    populateArray(myArray);
    displayArray(myArray);
-->
</SCRIPT>
</HTML>


Use string as the array indexer

<html>
<head>
<title>Mixing Notations</title>
<script language="javascript" type="text/javascript">
<!--
var x = new Array();
x["first"]  = "1st";
x["second"] = "2nd";
x["third"]  = "3rd";
alert(x.first + ", " + x.second + ", " + x.third);
//-->
</script>
</head>
<body>
<h1>Mixing Notations</h1>
</body>
</html>