Is there any way to create an array-like object in JavaScript, without using the built-in array? I\'m specifically concerned with behavior like this:
var sup
Is this what you're looking for?
Thing = function() {};
Thing.prototype.__defineGetter__('length', function() {
var count = 0;
for(property in this) count++;
return count - 1; // don't count 'length' itself!
});
instance = new Thing;
console.log(instance.length); // => 0
instance[0] = {};
console.log(instance.length); // => 1
instance[1] = {};
instance[2] = {};
console.log(instance.length); // => 3
instance[5] = {};
instance.property = {};
instance.property.property = {}; // this shouldn't count
console.log(instance.length); // => 5
The only drawback is that 'length' will get iterated over in for..in loops as if it were a property. Too bad there isn't a way to set property attributes (this is one thing I really wish I could do).