JavaScript Editor Ajax toolkit     Ajax website 

Main Page

All objects in JScript based on the Object object support expando properties, or properties that can be added and removed while the program is running.

Using the Object Object

These properties can have any name, including numbers. A name of a property that is a simple identifier can be written after a period that follows the object name, such as:

В CopyCode imageCopy Code
var myObj = new Object();
// Add two expando properties, 'name' and 'age' = "Fred"; 
myObj.age = 53;

You can also access an object's properties using the index operator, []. This is required if the name of the property is not a simple identifier, or if the name of the property is not known when you write the script. An arbitrary expression, including a simple identifier, inside square brackets can index the property. The names of all expando properties in JScript are converted to strings before being added to the object.

When using the index operator, the object is treated as an associative array. An associative array is a data structure that dynamically associates arbitrary data values with arbitrary strings. In this example, expando properties are added that do not have simple identifiers.

В CopyCode imageCopy Code
var myObj = new Object();
// This identifier contains spaces.
myObj["not a simple identifier"] = "This is the property value";
// This identifier is a number.
myObj[100] = "100";

Although the index operator is more commonly associated with accessing array elements, the index is always the property name expressed as a string literal when used with objects.

Array objects have a special length property that changes when new elements are added; in general, objects do not have a length property even when the index operator is used to add properties.

Notice the important difference between the two ways of accessing object properties.

Operator The property name is treated as Meaning that the property name

Period (.)

An identifier

Cannot be manipulated as data

Index ([])

A string literal

Can be manipulated as data

This difference becomes useful when you do not know the property names until runtime (for example, when you are constructing objects based on user input). To extract all the properties from an associative array, you must use the for ... in loop.

See Also


Object Object

Other Resources

Intrinsic Objects

JavaScript Editor Ajax toolkit     Ajax website