Reputation: 11545
are objects with properties the equivalent of associative arrays?
is it ok if the property names have punctuation characters?
like obj['http://google.com'] = { ... }
?
i can still access it like an array - obj['http://google.com']
, but not like an object because of the slashes and stuff.
basically i`m asking if it's considered a bad practice to use objects like this. if yes, is there any other alternative of getting associative arrays?
Upvotes: 0
Views: 91
Reputation: 151401
There's a risk using objects as associative arrays in JavaScript. Consider:
var foo = {};
function putFoo(x, v) {
foo[x] = v;
}
function getFoo(x) {
return foo[x];
}
putFoo("a", "blah");
console.log("a", getFoo("a")); // Yes, "a" is there.
console.log("b", getFoo("b")); // No, "b" is not there.
console.log("toString", getFoo("toString")); // what?
Everything is swell until you get to the last console.log
. toString
is a method in Object.prototype
from which object literals get their methods, so you'll get a function out on the console even though you never put anything named toString
in the object.
You can work around this by creating your object with Object.create(null)
. This will create an object that does not have a prototype, and so is not polluted by the members of Object
. (Documentation on Object.create.)
Here's a question that explores the performance issues. In brief creating an object with Object.create(null)
is more expensive than with {}
but accessing the keys on an object created by Object.create(null)
is faster than on an object created with {}
.
Upvotes: 2
Reputation: 664538
are objects with properties the equivalent of associative arrays?
Not exactly, for they are not ordered. They're more like a Map
.
is it ok if the property names have punctuation characters, like
obj['http://google.com'] = { ... }
?
Yes. As you could see, it works :-)
i can still access it like an array -
obj['http://google.com']
, but not like an object because of the slashes and stuff.
That's nothing array-specific. If the property name (of any object) is not a valid identifier (because it's a number or does contain a dot) or a dynamic value (like a variable), you have to use bracket notation for property access. In object literals, you can quote the keys.
Upvotes: 2