Visit Mozilla.org

Core JavaScript 1.5 Guide:Object Manipulation Statements

From MDC


Contents

[edit] Object Manipulation Statements

JavaScript uses the for...in, for each...in, and with statements to manipulate objects.

[edit] for...in Statement

The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows:

for (variable in object) {
   statements
}

Example
The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.

function dump_props(obj, obj_name) {
   var result = "";
   for (var i in obj) {
      result += obj_name + "." + i + " = " + obj[i] + "<br>";
   }
   result += "<hr>";
   return result;
}

For an object car with properties make and model, result would be:

car.make = Ford
car.model = Mustang

Arrays
Although it may be tempting to use this as a way to iterate over Array elements, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object, such as adding custom properties or methods, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.

[edit] for each...in Statement

for each...in is a loop statement introduced in JavaScript 1.6. It is similar to for...in, but iterates over the values of object's properties, not their names.

[edit] with Statement

The with statement establishes the default object for a set of statements. JavaScript looks up any unqualified names within the set of statements to determine if the names are properties of the default object. If an unqualified name matches a property, then the property is used in the statement; otherwise, a local or global variable is used.

A with statement looks as follows:

with (object) {
   statements
}

Example
The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

var a, x, y;
var r = 10;
with (Math) {
   a = PI * r * r;
   x = r * cos(PI);
   y = r * sin(PI/2);
}

Note: While using a with statement can make your program more concise, improper use of with can significantly slow down your program. See Core JavaScript 1.5 Reference:Statements:with.

« Previous Next »