Javascript:快速查找对象中的值(就像我们可以使用属性一样) [英] Javascript: Quickly lookup value in object (like we can with properties)
问题描述
我有一个对象,它有一对用于简单编码/解码的替换值(不是为了安全,只是为了方便;太复杂了,无法解释这一切)。它的格式为
I have an object that has pairs of replacement values used for simple encoding / decoding (not for security, just for a convenience; too complicated to explain it all here). It's in the form
var obj = {x: y,
x: y,
...
};
其中'x'是编码时的值,'y'是解码值。
where 'x' is the value when encoded and 'y' is the decoded value.
解码很简单:我循环遍历字符串的字符,并在对象中查找 charAt(i)
值通过括号: obj [str.charAt(i)]
。 (我要省略检查是否需要大写或小写版本(对象中的所有键/值都是小写),但这很简单。)
Decoding is simple: I loop through the characters of the string, and look up the charAt(i)
value in the object via brackets: obj[ str.charAt(i) ]
. (I'm leaving out the check to see whether we need an uppercase or lowercase version (all key/values in the object are lowercase), but that's simple enough.)
要进行编码,我当然必须在对象中查找值,而不是属性。目前,我正在使用循环遍历属性... in ...
循环并根据 charAt(i)<检查值/ code>价值。我目前的代码是:
To encode, I of course have to look for the value in the object, rather than the property. Currently, I'm looping through the properties with a for ... in ...
loop and checking the values against the charAt(i)
value. My current code is:
var i, j,
output = '',
str = 'Hello World!',
obj = {'s':'d',
'm':'e',
'e':'h',
'x':'l',
'z':'o',
'i':'r',
'a':'w',
'o':'!',
'-':' '};
for (i = 0; i < str.length; i++) {
for (j in obj) {
if (Object.prototype.hasOwnProperty.call(obj, j) &&
Object.prototype.propertyIsEnumerable.call(obj, j)) {
if (obj[j] === str.charAt(i)) {
output += j;
break;
} else if (obj[j].toUpperCase() === str.charAt(i)) {
output += j.toUpperCase();
break;
}
}
}
}
alert(output);
我天生就觉得应该有一种更有效的方法。 (当然有一个反向的对象,{y:x},是一个选项。但不是一个好的。)这是最好的方式,还是有更好的方法?本质上,我希望能够做到 var prop = obj [value]
就像我能做的那样 var value = obj [prop]
。
I innately feel like there should be a more efficient way of doing this. (Of course having a reversed object, {y: x}, is an option. But not a good one.) Is this the best way, or is there a better? In essence, I'd love to be able to do var prop = obj[value]
just like I can do var value = obj[prop]
.
推荐答案
预先循环一次以创建反向地图效率更高:
It's more efficient to loop just once beforehand to create a reverse map:
var str = "Hello World!",
output = '',
map = {
"s":"d", "m":"e",
"e":"h", "x":"l",
"z":"o", "i":"r",
"a":"w", "o":"!",
"-":" "
},
reverseMap = {}
for (j in map){
if (!Object.prototype.hasOwnProperty.call(map, j)) continue
reverseMap[map[j]] = j
}
output = str.replace(/./g, function(c){
return reverseMap[c] || reverseMap[c.toLowerCase()].toUpperCase()
})
console.log(output)
而不是做 str.length * map.length
,你将做 map.length + str.length
操作。
Instead of doing str.length * map.length
, you'll do map.length + str.length
operations.
这篇关于Javascript:快速查找对象中的值(就像我们可以使用属性一样)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!