What happens when a javascript array is processed as an object?

the index variable below is not initializing correctly because f () will return material other than numbers, such as strings. So what's the worst thing that can happen here? My testing seems to indicate that it has no effect, but now I'm wondering ...

function index(o, f) {
    var index = []; // should be index = {};
    each(o, function(k, v, o) { index[f(k, v, o)] = v; });
    return index;
}
+3
source share
4 answers

Javascript arrays are special objects that automatically set a property lengthand inherit Array.prototype.
If you are not using a property length, there is no harm in treating the array as an object.

+4
source

- , . , length , .

[] {}

+2

, JavaScript. , , (... in to iterate, myarray [key] ). , , , .

0

"f() , , "

If f () returns only strings, then you should go, you just use your array as an object and add properties. The only drawback is that the array itself remains empty, so for example, you cannot calculate how many elements you have added.

If f () can return both strings and numbers, this will create a mess. A loop sometimes fills an array, sometimes an object’s properties.

I'm not sure what you mean by “like strings”, but if the result of f () is neither a number nor a string, then it will not work.

0
source

Source: https://habr.com/ru/post/1765327/


All Articles