JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.10

Objects with Indexed Properties

This section provides a quick description of indexed properties and indexed methods. A tutorial example is provided on how to create and access indexed properties and indexed methods.

JavaScript also supports objects with indexed properties with the following features:

  • An indexed property is a property with an index number instead of a property name.
  • An indexed property can not be accessed with the dot (.) operator.
  • An indexed property can be accessed with the associate array operator (['index']).
  • An indexed property can also be accessed with the array operator ([index]).
  • An indexed property can be assigned with a function to become an indexed method.

Here is a tutorial example on how to define and access object's indexed properties and indexed methods in two formats: array format and associate array format:

<html>
<!-- Object_Indexed_Properties.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Objects with Indexed Properties</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Using "this" to get the properties
function myToString() {
   return '"'+this.title + '" by '+this.author;
}

   // Using object literal format
   var myBook = {
      author: "Herong Yang",
      title: "JavaScript Tutorials",
      3: 2008,
      price: "Free",
      4: myToString
   };

   // Adding a new indexed property   
   myBook[9] = "Programming";

   // An index property can not be accessed with (.)
   // document.writeln("myBook.3: "+myBook.3);

   // Getting indexed property values
   document.writeln("myBook[3]: "+myBook[3]);
   document.writeln("myBook['3']: "+myBook['3']);
   document.writeln("myBook[4]: "+myBook[4]);
   document.writeln("myBook[9]: "+myBook[9]);

   // Checking property data types
   document.writeln();
   document.writeln(myBook[4]());
</script>
</pre>
</body>
</html>

The output of this tutorial example matches my expectation:

myBook[3]: 2008
myBook['3']: 2008
myBook[4]: function myToString() {
    return "\"" + this.title + "\" by " + this.author;
}
myBook[9]: Programming

"JavaScript Tutorials" by Herong Yang

Sections in This Chapter

What Is an Object?

Objects of "Object" Data Type

Adding and Deleting Object Own Properties

Adding and Deleting Object Own Methods

Using "this" Keyword to Represent Current Object

Object Literals of the "Object" Type

Objects and Associate Arrays

Objects with Indexed Properties

Differences between "Object" and "Array"

Using "Array" Objects as "Object" Objects

Dr. Herong Yang, updated in 2008
Objects with Indexed Properties