Javascript newbie here. I currently have an associative array in the following format:
StringA: number,
StringB: number
Is it possible to map multiple strings to the same number? Something like this (some numbers may have a different number of Strings mapped to them):
StringA, StringB, StringC: number,
StringD, StringE: number,
StringF, StringG, StringH, StringI: number
Basically, I want holder to have the same value whether I write var holder = arr[StringA]
or var holder = arr[StringC]
. If it's not possible could someone point me in the right direction? Any help would be greatly appreciated!
You could use an object with a value for the object with multiple keys for one object.
Basically this creates a reference to the shared object. Then you could change the value inside of the object.
var temp = { value: 42 }, object = { a: temp, b: temp, c: temp }; console.log(object.a.value); // 42 object.b.value = 7; console.log(object.c.value); // 7
Basically Js don't have associative array they are objects. Read this: http://www.w3schools.com/js/js_arrays.asp
You need pointers to achive this, but JS not have pointers. But ther is a way to use pointers: use objects.
var assoc = []; assoc["stringA"] = { value: 1}; assoc["stringB"] = assoc["stringA"]; assoc["stringC"] = assoc["stringA"]; assoc["stringD"] = { value: 10}; assoc["stringE"] = assoc["stringD"]; console.log("A: "+assoc["stringA"].value); console.log("B: "+assoc["stringB"].value); console.log("C: "+assoc["stringC"].value); console.log("D: "+assoc["stringD"].value); console.log("E: "+assoc["stringE"].value); console.log("======== modify value ======"); console.log("\\nModify A to 2") assoc["stringA"].value = 2; console.log("B: "+assoc["stringB"].value); console.log("C: "+assoc["stringB"].value); console.log("\\nModify E to 20") assoc["stringE"].value = 20; console.log("D: "+assoc["stringD"].value); console.log("E: "+assoc["stringE"].value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.