mellowsoon
mellowsoon

Reputation: 23301

JavaScript: Use Object As Array

Are there any pitfalls to code like this?

var Foo = function() {
    this.bar = function() { return 'bar'; };
};

var f = new Foo();
f[0] = 'hi';
f[1] = 'there';

Note that I'm creating a new function object with some misc properties, and then I'm treating the object like an array. Also how are the array values being stored in the object? Are 0 and 1 treated like property names?

Upvotes: 2

Views: 2089

Answers (3)

guilin 桂林
guilin 桂林

Reputation: 17412

If you want to extend Array behavious please use : Array.prototype.yourfunc = function()....

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828090

Well, yes, 0, and 1 will be just two property names.

When you assign a property with the bracket notation, the expression between the brackets will be converted to String, and that string will be used as the property name.

In fact, even the indexes for real arrays are just that, properties:

var realArray = ['a'];
realArray.hasOwnProperty('0'); // true

The difference is that real array objects on every property assignment that correspond to a valid index[1], track internally the value of their length property.

That's one of the reasons why "subclassing" array objects is difficult, even with the new ECMAScript 5 extensions, or at the moment also with the proposed ECMAScript-Harmony Proxies 2 3, can't be completely done, in a stanard way.

That can be a problem, depending on how you plan to iterate the numeric properties.

If you enumerate the properties with the for-in statement, other members will appear, not just the numeric properties.

[1] A valid array index is any unsigned 32-bit integer in the range of 0 to (2^32)-1.

Upvotes: 8

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68172

I think you might have problems if you try to loop through that with a for in loop; the loop will also get bar. There are ways around this, so you just have to be careful.

Upvotes: 1

Related Questions