Array Indexing
Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes. In the example below, the variable person uses a numbered index, while the variable people uses the named index. Note the returned results:
person[0]; <== returns "John"
person.length; <== returns 3
people[0]; <== returns undefined
people.length; <== returns 0
HTML file: |
Displayed by browser: |
<body>
<h4>Using numbered indexes:</h4>
<p id="demo"></p>
<hr />
<h4>Using named indexes:</h4>
<p id="demo1"></p>
<script>
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
var people = [];
people["firstName"] = "Mary";
people["lastName"] = "Dell";
people["age"] = 64;
document.getElementById("demo1").innerHTML =
people[0] + " " + people.length;
</script>
</body>
|
Using numbered indexes:
Using named indexes:
|