I want to create something like a dictionary object where given a name as key, it should output its value.
Eg
dict["jerry"] should output 20 as value.
Or
var name = "jerry";
dict[name] should output 20 as value
My code.
var totalAdditions = [];
totalAdditions.push({name:statsObj.author.login, value: additions});
//statsObj.author.login contains "jerry"
console.log(obj.login); //also contains value "jerry"
console.log(totalAdditions[obj.login]); //returns undefined??
JavaScript doesn't have "associative arrays." It does have objects, which can do what you want, and Map
(as of ES2015), which can also do what you want.
Object:
var dict = Object.create(null); // Not {} so it doesn't inherit props like // "toString", "valueOf", etc. var name = "jerry"; dict["jerry"] = 20; console.log(dict[name]); // 20
ES2015+ Map
:
let dict = new Map(); var name = "jerry"; dict.set("jerry", 20); console.log(dict.get(name)); // 20
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.