Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens when javascript array is treated like an object?

Tags:

javascript

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;
}
like image 348
Damien Avatar asked Jun 23 '26 00:06

Damien


1 Answers

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.

like image 200
SLaks Avatar answered Jun 24 '26 13:06

SLaks