如何以快速/优化的方式从大型数组列表中找到密钥?
var error_constant_ENGLISH = {
group0: {'xyz','1234'},
group1: {'Temporarily Unavailable',
'Invalid number',
'You have reached the voice mail of P P P',
'We are sorry then number you have dialed is not valid please try again',
'Large sentences'},
group2: {'abc','def large sentences'}
}
var error_constant_FRENCH = {
group0: {'xyz','1234'},
group1: {'Temporarily Unavailable',
'Invalid number',
'You have reached the voice mail of P P P',
'We are sorry then number you have dialed is not valid please try again',
'Large sentences'},
group2: {'abc','def large sentences'}
}
// Assume:
var language='ENGLISH';
var reason_phrase='Invalid number'
search_in_error(reason_phrase);
// Expected output: group1
答案 0 :(得分:1)
这不是数组而是对象! 用" {}"
附上的对象group1: {
var1:'Temporarily Unavailable',
var2:'Invalid number',
var3:'Large sentences'
},
数组附有" []"并且只允许数字索引0,1,2,
group1: [
'Temporarily Unavailable',
'Invalid number',
'Large sentences'
],
因此,如果您将其更改为数组,则可以使用此
function search_in_error(errormessage, language){
var myObj = self["error_constant_"+language];
for(var name in myObj){
var myArr = myObj[name];
if(myArr.indexOf){ if(myArr.indexOf(errormessage)>-1){ return name; } }
else{ for(var i=0; i<myArr.length; i++){ if(errormessage==myArr[i]){return name;} } }
}
}
这样称呼:
search_in_error(reason_phrase, language);
您必须正确定义语言对象:
var error_constant_ENGLISH = {
group1:[
'aaaaa',
'bbb'
],
group2:[
'Temporary Unavailable',
'Invalid Number'
]
};
答案 1 :(得分:1)
使用这种数据结构,它不能比O(n×m)快。假设错误组是数组。
function search_in_error(phrase){
var errorGroup = window["error_constant_" + language],
errors;
for(var key in errorGroup){
if (!errorGroup.hasOwnProperty(key)){
continue;
}
errors = errorGroup[key];
for (var i = 0; i < errors.length; i++){
if (errors[i] === phrase)
return key;
}
}
return null;
}