New version 0.3a attached:
- Fixed a problem with for ... in constructs due to new methods of the Array object defined as enumerable properties.
Information for developersThe problem: Adding new methods to the Array object with usual definitions such as:
Array.prototype.foo = function()
{
// ...
};
is problematic because the newly defined methods are created as enumerable properties of Array. Subsequent for ... in constructs, such as:
var a = new Array;
// ...
for ( var i in a )
{
// ...
}
will most likely fail because *all* enumerable properties of Array.prototype will be iterated along with the elements of the 'a' instance. For more information on the for ... in statement and its problems please refer to the following document on Mozilla's Development Network:
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...inQuoted from the above document:
for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index when iterating over arrays where the order of access is important.So the bottom line is: do not use for ... in in your scripts. I recognize that I use these constructs sometimes, so I have to apply this rule to myself. By the way, even worse than for...in is the 'with' statement, which is considered poison in ECMAScript-5:
https://developer.mozilla.org/en/JavaScript/Reference/Statements/withThe solution to this problem is defining the new Array methods with the
Object.defineProperty function, which is part of ECMAScript 5th Edition. This is what I have done in version 0.3a of the script. Fortunately, PixInsight's JavaScript runtime (= Mozilla's SpiderMonkey JS engine version 1.8.5) is fully compliant with the ECMA 262-5 standard.