如何在JavaScript中创建双向映射,或通过其他方式交换值? [英] How can I create a two-way mapping in JavaScript, or some other way to swap out values?
问题描述
我目前需要临时交换JavaScript字符串中的值,因此,我将需要一个双向的map/hash对象.
I currently have a need to temporarily swap out values in a JavaScript string, and therefore I will need to have a two-way map/hash thing.
例如,假设我想将\*
更改为__asterisk__
(这只是一个示例,这不是我实际上要执行的操作).我必须能够将*
映射到__asterisk__
(以交换原始字符串中的值),但是然后我还必须能够将__asterisk__
映射回*
(以返回原始字符串).
For example, let's say I want to change \*
to __asterisk__
(this is just an example, it's not what I'm actually trying to do). I'll have to be able to map *
to __asterisk__
(to swap out the value in the original string), but then I'll also have to be able to map __asterisk__
back to *
(to get the original string back).
这里有一些我想要的快速伪伪代码,因此您可以更好地理解它:
Here's some quick pseudo-ish code of the kind of thing that I'm looking for, so you can understand it better:
var myString = 'this is \* a test';
// ???
var twoWayMap = new TwoWayMap('*' <---> '__asterisk__', '%' <---> '__percent__', ...);
var newString = myString.replace(/\\(.)/g, function(m, c) {
return twoWayMap.getKey(c);
});
// newString is now 'this is __asterisk__ a test'
// ... later in the code ...
var oldString = newString.replace(/__([^_]+)__/g, function(m, c) {
return twoWayMap.getValue(c);
});
// oldString is now 'this is * a test'
这是我到目前为止一直在考虑和尝试的事情:
This is what I've thought about and tried so far:
var twoWayMap = {'*': '__asterisk__', '%': '__percent__', ...};
// getKey would be like this:
twoWayMap[c];
// getValue would be like:
var val; for (var x in twoWayMap) { if (twoWayMap[x] === c) { val = x; break } }
一个明显的问题是,获取价值的方法太复杂了,我不想每次都要反向查找时都必须写出全部内容.
The obvious problem with this is that the way to get by value is much too complicated, and I don't want to have to write out the whole thing every single time I have to reverse lookup.
我只是想知道:有什么方法可以解决这个问题而无需求助于遍历一个对象?如果没有,有什么方法可以使它更容易或更清洁?
I just wanted to know: Is there any way to solve this problem without resorting to looping through an object? If not, is there any way to make it easier or cleaner?
推荐答案
使用两个对象.一个对象包含* -> _asterisk_
映射,另一个对象包含_asterisk_ -> *
.
Use two objects. One object contains the * -> _asterisk_
mapping, the other object contains _asterisk_ -> *
.
var forwardMap = {'*': '__asterisk__', '%': '__percent__', ...};
var reverseMap = {};
for (var key in forwardMap) {
if (forwardMap.hasOwnProperty(key)) {
reverseMap[forwardMap[key]] = key;
}
}
这篇关于如何在JavaScript中创建双向映射,或通过其他方式交换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!