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.
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.
You can now use Map data structure. It was introduced in JavaScript via ES6 and allows to create collections of key-value pairs. Unlike objects, a map object can hold both objects and primitives as keys and values. Here is example:
const items = new Map();
// add items
items.set('πΆ', 'Dog');
items.set('π¦
', 'Eagle');
items.set('π', 'Train');
items.set(45, 'Number');
items.set(true, 'Boolean');
// iterate over map
for (const [key, value] of items) {
console.log(`${key}: ${value}`);
}
Output:
πΆ: Dog
π¦
: Eagle
π: Train
45: Number
true: Boolean
More examples
Related
According to MDN, the size property of a Map object should represent the number of entries the Map object has. However, if I create an empty Map and use the bracket notation (not sure what the formal name for this is) to add a key/value pair, the size property is not updated. However, if I use the Map.set(key, value) function, then the property is updated. Why is this?
Example:
var ex = new Map();
ex['key1'] = 'value1';
ex.set('key2', 'value2');
After running this, ex.size returns 1.
Because adding a property to the map object is not the same as adding an element to the map (and vice versa). Try ex.get('key1') (and ex['key2']). Only Map#set adds an element to the map. Maybe it becomes clearer if you consider this poor and limited implementation of Map:
class Map {
constructor() {
this._items = {};
}
set(key, value) {
this._items[key] = value;
}
get(key) {
return this._items[key];
}
get size() {
return Object.keys(this._items).length;
}
}
Adding a property to an instance of the class would not affect this._items, which is where the map entries are stored.
You can add arbitrary properties to basically any object in JavaScript, but that doesn't mean that the object is doing anything with them.
The most confusing case is probably arrays. Only properties whose numeric value is between 0 and 2^32 are considered "elements" of the array. So when I do
var arr = [];
arr.foo = 42;
then arr.length will still be 0.
Because ex['key1'] = 'value1'; just added a new property key1 to the object ex (that happens to be of type Map).
It does not affect the content of the actual Map.
Whatβs the difference between β{}β and β[]β while declaring a JavaScript array?
Normally I declare like
var a=[];
What is the meaning of declaring the array as var a={}
Nobody seems to be explaining the difference between an array and an object.
[] is declaring an array.
{} is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.
The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.
When you declare
var a=[];
you are declaring a empty array.
But when you are declaring
var a={};
you are declaring a Object .
Although Array is also Object in Javascript but it is numeric key paired values.
Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.
So if you want Some values where you need to use numeric keys use Array.
else use object.
you can Create object like:
var a={name:"abc",age:"14"};
And can access values like
console.log(a.name);
var a = [];
it is use for brackets for an array of simple values.
eg.
var name=["a","b","c"]
var a={}
is use for value arrays and objects/properties also.
eg.
var programmer = { 'name':'special', 'url':'www.google.com'}
It can be understood like this:
var a= []; //creates a new empty array
var a= {}; //creates a new empty object
You can also understand that
var a = {}; is equivalent to var a= new Object();
Note:
You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.
they are two different things..
[] is declaring an Array:
given, a list of elements held by numeric index.
{} is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more # This Article
Syntax of JSON
object = {} | { members }
members = pair | pair, members
pair = string : value
array = [] | [ elements ]
elements = value | value elements
value =
string|number|object|array|true|false|null
In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.
For an array:
var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();
As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.
But as we all know JavaScript is strange, so here are some weird bits:
array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!
This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.
So what are Objects?
Objects in JavaScript are just like arrays but the "index" can be any string.
var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK
You can even opt to not use the square brackets when working with objects!
console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";
You can go even further and define objects like so:
var newObject = {
a: 2,
};
newObject.a === 2; // true
[ ] - this is used whenever we are declaring an empty array,
{ } - this is used whenever we declare an empty object
typeof([ ]) //object
typeof({ }) //object
but if your run
[ ].constructor.name //Array
so from this, you will understand it is an array here Array is the name of the base class.
The JavaScript Array class is a global object that is used in the construction of arrays which are high-level, list-like objects.
I'm trying to learn javascript (coming from Delphi/pascal) and am unclear about the similarities and differences between object properties and array values. I did try searching the archives and the web for this answer.
Consider the following code:
function Show(Arr) {
var str ='';
for (var Val in Arr) {
str += Val + '::' + Arr[Val] + '\n';
}
return str;
}
var str = '';
var A1 = ["Yellow", "Red", "Blue"];
var A2 = {"color":"red", "Size": 5, "taste":"sour"}
alert(Show(A1));
//OUTPUTS:
// 0::Yellow
// 1::Red
// 2::Blue
A1.push("Green");
alert(Show(A1));
//OUTPUTS:
// 0::Yellow
// 1::Red
// 2::Blue
// 3::Green
alert('Length: '+A1.length);
//OUTPUTS:
// Length: 4
alert(Show(A2));
//OUTPUTS:
// color::red
// Size::5
// taste:sour
alert('Length: '+A2.length);
//OUTPUTS:
// Length: undefined
A2.push("Green");
//ERROR --> execution stops on jsfiddle.net.
alert("OK"); //<-- never executed
alert(Show(A2)); //<-- never executed
I know that almost everything is an object in javascript. I have been reading here (http://javascript.info/tutorial/objects) and here (http://www.w3schools.com/js/js_objects.asp).
I see that an array can be accessed by index, e.g. A1[3] --> Blue, as in other languages. But I see also that a property can be accessed this way, e.g. A2["Size"] --> 5. So at first blush, it looks like array values and property values are essentially the same. But arrays can be extended with a .push(value) command, whereas properties can't.
It is coincidence that my Show function works for both arrays and objects?
Actually, as I have written this and researched the topic, is it just that all arrays are objects, but not all objects are array? So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?
Any help clarifying this would be appreciated. Thanks.
So at first blush, it looks like array values and property values are essentially the same.
Array entries and object properties are indeed the same thing, because JavaScript's standard arrays aren't really arrays at all, they're just objects with some added features. Two of those features are the special length property, and the push function, which is why you don't see those with A2.
Your observation about bracketed notation is particularly spot-on. In JavaScript, you can access object properties using bracketed notation and a string, like this:
var o = {answer: 42};
console.log(o['answer']); // 42
It's not well-known that this is exactly what you're doing when using an array "index":
var a = ['a', 'b', 'c'];
console.log(a[1]); // b
The 1 we're using with a[1], technically according to the specification, is coerced to a string (a["1"]), and then that property name is used to look up the property on the object.
So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?
No, for-in works the same with all objects. It iterates the names of the enumerable properties of the object. Whether you're using an array or any other object doesn't matter.
Note that not all properties are enumerable. For instance, Array#length isn't, nor is Array#push or Object#toString or any of the other built-in properties of objects.
But for instance, you can see that for-in is the same for arrays as for other objects like this:
var a = ['zero']; // An array with one entry
a.answer = 42; // We've added a property to the object that isn't an array entry
console.log(a.length); // 1, because `length` only relates to array "indexes" as
// defined by the specification
var key;
for (key in a) {
console.log(key + "=" + value);
}
// Shows (in *no reliable order*):
// 0=zero
// answer=42
More about for-in:
Myths and realities of for..in (on my blog)
My answer to the question For each in array, how to do that in JavaScript? here on SO
What is the JavaScript equivalent function for CreateObject("Scripting.Dictionary")?
I have to convert following two statements from VBScript to JavaScript, anyone can help me to find a solution.
Set oInvoicesToCreate = CreateObject("Scripting.Dictionary")
If Not oInvoicesToCreate.Exists(cInvoiceID) Then
oInvoicesToCreate(CStr(cInvoiceID)) = ""
End If
var oInvoicesToCreate = {};
if(oInvoicesToCreate[cInvoiceID] === undefined){
oInvoicesToCreate[cInvoiceID] = "";
}
You probably don't want to check the hasOwnProperty method because you'll want to check if anything in the prototype chain has that property as well and not overwrite it. checking with the []s will let you know if any property on any prototype items have the property as well.
As bluetoft says in this answer, in Javascript you can use a plain object instead. However, there are a few differences between them that you should be aware of:
First, a Dictionary's keys can be any type:
var dict = new ActiveXObject('Scripting.Dictionary');
dict(5) = 'Athens';
console.log(dict('5')); //prints undefined
whereas any value used for a Javascript object's key will be converted to a string first:
var obj = {};
obj[5] = 'Athens';
console.log(obj['5']); // prints 'Athens'
From MDN:
Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. For example, in the above code, when the key obj is added to the myObj, JavaScript will call the obj.toString() method, and use this result string as the new key.
Second, it is possible to set a Dictionary to treat differently cased keys as the same key, using the CompareMode property:
var dict = new ActiveXObject('Scripting.Dictionary');
dict.CompareMode = 1;
dict('a') = 'Athens';
console.log(dict('A')); // prints 'Athens'
Javascript key access via [] doesn't support this, and if you want to treat differently-cased keys as the same, you'll have to convert the potential key to lowercase or uppercase before each read or write.
For your specific scenario, neither of these differences matter, because the keys are numeric strings (1) which have no case (2).
In my script there is a need to create a hash table, and I searched in google for this. Most of the folks are recommending JavaScript object for this purpose. The The problem is some of the keys in the hash table have a "." in them. I am able to create these keys easily with the associative arrays.
I don't understand why associative arrays are bad. The first thing that is mentioned on the sites that I looked at is the length property.
I am coming from the Perl background, where I used hashes. Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, and add a key-value pair. If these are my common uses, can I safely use an associative array?
In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:
var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';
alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'
If you're using them already and they work, you're safe.
In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays. It is also much easier to construct an object than using an associative array:
var obj = {"my.key": "myValue"};
vs.
var obj = [];
obj["my.key"] = "myValue";
Therefore never use the array object for this, but just the regular object.
Some functionality:
var obj = {}; // Initialized empty object
Delete a key-value pair:
delete obj[key];
Check if a key exists:
key in obj;
Get the key value:
obj[key];
Add a key-value pair:
obj[key] = value;
Because there is no such thing as built-in associative arrays in JavaScript. That's why it's bad.
In fact, when you use something like:
theArray["a"] = "Hello, World!";
It simply creates a property called "a" and set its value to "Hello, World!". This is why the length is always 0, and why the output of alert(theArray) is empty.
Actually, an "associative array" is pretty much the same as an "array-like object" in ECMAScript. Even arrays are objects in ECMAScript, just with the exception to have numeric keys (which are still strings in the background) and a .length property, along with some inherited methods from Array.prototype.
So, a Perl hash and an ECMAScript object behave similarly. You might not know that you can access object properties not only via a dot, but also with brackets and strings, like
var myObj = { foo: 42 };
myObj.foo; // 42
myObj['foo']; // 42
Knowing that, you can also use keys with .
var myObj = { };
myObj['hello.foo.world'] = 42;
Of course, you can access that key only with the bracket notation.
You can use . in key names on JavaScript objects (AKA associative arrays) if you'd like; they're accepted without issue. The minor drawback is you can't use shortcut notations with the dotted keys, e.g.
var x = {};
x['hello'] = 'there';
alert(x.hello);
is perfectly acceptable and will pop up an alert with 'there' in it. But if you use a dotted name:
var x = {};
x['this.is'] = 'sparta';
alert(x.this.is);
will fail, as JavaScript will look for an attribute named this in the x object, which does not exist. There is only the this.is attribute.
There isn't an associative array. It's just an object.
foo.bar; // Equivalent to...
foo["bar"]; // Looks like associative array.
For the sake of convenience of using data, there should be no difference between an object and an array. You can think of it as an object or you can think of it as an associative array. At the end, you can just think of everything as data.
For PHP, [ ] accepts 0, 1, or more items(array), and it is called an associative array. It is JSON in PHP's coat:
$data = ["message"=>[ "id"=>405, "description"=>"Method not allowed.", "detail"=>[]], "object" => []];
For JavaScript, { } accepts 0, 1, or more items(array), and it is called an object. This data format is JSON:
data = {"message": { "id":405, "description":"Method not allowed.", "detail" : {}}, "object" : {}};
I just call them data. The simplest way to describe data is JSON, or its variants.