Damien
Damien

Reputation: 115

what happens when javascript array is treated like an object?

the index variable below is incorrectly initialized because f() will be returning stuff other than numbers, like strings. So what's the worst that can happen here? My testing seems to indicate that it has no effect, but now I am wondering...

function index(o, f) {
    var index = []; // should be index = {};
    each(o, function(k, v, o) { index[f(k, v, o)] = v; });
    return index;
}

Upvotes: 3

Views: 1783

Answers (4)

Christophe
Christophe

Reputation: 28154

"f() will be returning stuff other than numbers, like strings"

If f() only returns strings, then you're good to go, you're just using your array as an object and adding properties. The only downside is that the array itself remains empty, so for example you cannot count how many items you have added.

If f() can return both strings and numbers, it's going to create a mess. The loop will populate sometimes the array, sometimes the object properties.

I am not sure what you mean by "like strings", but if what f() returns is neither a number nor a string then it's not going to work.

Upvotes: 0

MooGoo
MooGoo

Reputation: 48260

An array is an object, thus it can be treated as such without much side effects. Doing so however might result in some confusion, as the length property does not count non-numeric keys, and all the array prototype functions will likewise ignore them.

Just change [] to {}

Upvotes: 2

matt snider
matt snider

Reputation: 4113

You'll be creating an associative array, which is a valid JavaScript structure. Although, it is technically different than an object, you can interact with the array just like you would an object (for ... in to iterate, myarray[key] to fetch values). You may want to consider returning an object instead of an array if you suspect some keys will be strings.

Upvotes: 0

SLaks
SLaks

Reputation: 887867

Javascript arrays are special objects that have an automatically set length property and inherit Array.prototype.
Unless you use a length property, there is no harm in treating an array as an object.

Upvotes: 4

Related Questions