简体   繁体   English

Javascript关联数组如何将多个字符串映射到数字

[英]Javascript associative array how to map multiple strings to a number

Javascript newbie here. 这里的Javascript新手。 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] . 基本上,无论我写var holder = arr[StringA]还是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. 基本上Js没有关联数组,它们是对象。 Read this: http://www.w3schools.com/js/js_arrays.asp 阅读: http//www.w3schools.com/js/js_arrays.asp

You need pointers to achive this, but JS not have pointers. 你需要指向这个,但JS没有指针。 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM