Javascript:快速查找对象中的值(就像我们可以使用属性一样)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10974493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Quickly lookup value in object (like we can with properties)
提问by Marcus Hughes
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,
...
};
where 'x' is the value when encoded and 'y' is the decoded value.
其中“x”是编码时的值,“y”是解码后的值。
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.)
解码很简单:我遍历字符串的字符,并charAt(i)
通过括号查找对象中的值:obj[ str.charAt(i) ]
。(我省略了检查我们是否需要大写或小写版本(对象中的所有键/值都是小写),但这很简单。)
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:
要编码,我当然必须在对象中查找值,而不是属性。目前,我正在使用循环遍历属性for ... in ...
并根据值检查charAt(i)
值。我目前的代码是:
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);
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]
.
我天生就觉得应该有一种更有效的方法来做到这一点。(当然,使用反向对象 {y: x} 是一种选择。但不是一个好方法。)这是最好的方法,还是有更好的方法?从本质上讲,我希望能够var prop = obj[value]
像我能做的那样做var value = obj[prop]
。
采纳答案by Ricardo Tomasi
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)
Instead of doing str.length * map.length
, you'll do map.length + str.length
operations.
而不是做str.length * map.length
,你会做map.length + str.length
操作。
回答by kennebec
A reverse encoder would make more sense, but you can write a replace function without all the hasOwnProperty etc.tests.
反向编码器会更有意义,但是您可以在没有所有 hasOwnProperty 等测试的情况下编写替换函数。
var str= 'Hello World!',
obj={
's':'d',
'm':'e',
'e':'h',
'x':'l',
'z':'o',
'i':'r',
'a':'w',
'o':'!',
'-':' '
}
str= str.replace(/./g, function(w){
for(var p in obj){
if(obj[p]=== w) return p;
if(obj[p]=== w.toLowerCase()) return p.toUpperCase();
};
return w;
});
returned value: (String) Emxxz-Azixso
返回值:(字符串)Emxxz-Azixso
回答by nhahtdh
You can create a reversed version of the mapping programmatically (instead of by hand) and use it instead.
您可以通过编程方式(而不是手动)创建映射的反向版本并使用它。
var rev = {}
for (key in obj)
rev[obj[key]] = key
回答by Andy
If you're looking for array keys check here.
如果您正在寻找数组键,请在此处查看。
https://raw.github.com/kvz/phpjs/master/functions/array/array_keys.js
https://raw.github.com/kvz/phpjs/master/functions/array/array_keys.js
function array_keys (input, search_value, argStrict) {
var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = '';
if (input && typeof input === 'object' && input.change_key_case) {
return input.keys(search_value, argStrict);
}
for (key in input) {
if (input.hasOwnProperty(key)) {
include = true;
if (search) {
if (strict && input[key] !== search_value) include = false;
else if (input[key] != search_value) include = false;
}
if (include) tmp_arr[tmp_arr.length] = key;
}
}
return tmp_arr;
}