I'm working with some people are are used to making "associative arrays" in JavaScript like this:
var arr = new Array();
arr.prop_1 = "asdf";
or
arr['prop 2'] = "1234";
It works just like an object because it is. for...in
loops can be used and accessing the properties is fine using a dot or a square brace. the lack of native array methods seems not to be lamented. I find it sort of semantically irritating however. Maybe I'm being picky, but I want a good argument for arresting the use of this syntax, but I can't understand how to start. Any suggestions?
Best Answer
Which do you think looks cleaner?
or
?
Also, if you do something like this:
Then
object.length
will still be 0, which is definitely not what you would expect. You might think this is just a fake example that will never come up in real life, but look at this:This will log:
Alternatively, you could make an analogy to any other object, like a function:
Anyone could immediately tell you that that is wrong, and using an array is just as wrong.