Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript map variable

Tags:

c++

javascript

I'm looking to implement a c++ map variable type in JavaScript but can not seeing anything on the internet. When I used SFML I created a std::map of type String and SFML::Texture so I could store a texture inside of the map and get the texture value by using the key, how would I implement this into JavaScript?

The reason I want to do this is I want to load all image assets at the start of my HTML5 game, and then I can call on the image map and get the image reference using the key.

like image 546
Canvas Avatar asked May 21 '26 22:05

Canvas


1 Answers

The standard way in JavaScript is just an object:

var map = {};
map["any key you like"] = any_value_you_like;

// Also:
map.any_name_you_like_that_fits_identifer_name_rules = any_value_you_like;

The keys are always strings (for now, ES6 will add symbol/name keys), the values are any JavaScript value. When you use dot notation (obj.foo), the property name is a literal (and subject to JavaScript's rules for IdentifierName); when you use brackets notation and a string (obj["foo"]), the property name can be just about anything (and can be the result of any expression, such as a variable lookup).

Example: Live Copy

var map = {};
map["a"] = "alpha";
map["b"] = "beta";
map["c"] = "gamma";

["a", "b", "c"].forEach(function(key) {
  display("map['" + key + "'] = " + map[key]);
});

Output:

map['a'] = alpha
map['b'] = beta
map['c'] = gamma

dandavis raises an interesting point: When you create an object via {}, it inherits properties from Object.prototype, but as of ES5 you can use Object.create(null), which doesn't:

var map = Object.create(null);
map["any key you like"] = any_value_you_like;

// Also:
map.any_name_you_like_that_fits_identifer_name_rules = any_value_you_like;

That way, if you happen to have the potential for keys with names like toString or valueOf (which are on Object.prototype), you won't get false positives when looking them up on an object where you haven't set them explicitly.

like image 56
T.J. Crowder Avatar answered May 24 '26 11:05

T.J. Crowder