我在sessionStorage
中有一个JavaScript数组,当我执行sessionStorage.getitem('states')
时,我会这样:
"{
"TamilNadu": [
"Chennai",
"Trichy",
"Madurai"
],
"Andhra": [
"Hyderabad",
"Vizhag"
],
"Karnataka": [
"Bangalore",
"Mysore",
"Darwad"
],
"Maharashtra": [
"Mumbai",
"Pune"
]
}"
现在我的要求是从城市名称获取州名。
例如,如果我将"Mumbai"
作为参数传递给函数,则该函数应读取此sessionstorage
值并返回"Maharashtra"
。
你能帮我解决一下这个问题吗?
答案 0 :(得分:1)
此代码:
sessionStorage.getitem('states')
返回一个字符串。你必须用:
解析它var obj = JSON.parse(sessionStorage.getitem('states'))
下一个使用方括号或点访问对象属性:
for (var attr in obj) {
if (obj.hasOwnProperty(attr) && obj[attr][0] == 'Mumbai') {
return attr;
}
}
return null;
答案 1 :(得分:1)
function getStateByCityName (cityName) {
var states = {};
try {
states = JSON.parse(sessionStorage.getitem('states'));
} catch (e) {
}
for (var state in states) {
for (var i = 0; i < states[state].length; i ++) {
if (states[state][i] == cityName)
return state;
}
}
return null;
}
答案 2 :(得分:1)
或者只使用if (states[state].indexOf(cityName) !== -1)
getStateByCityName(cityName) {
var statesRaw = sessionStorage.getitem('states');
var states = JSON.parse(statesRaw);
for (var state in states) {
if (states[state].indexOf(cityName) !== -1) {
return state;
}
}
return false;
}
或者在EcmaScript 5循环风格中:))
getStateByCityName(cityName) {
var statesRaw = sessionStorage.getitem('states');
var states = JSON.parse(statesRaw);
Object.keys(states).forEach(function(state) {
if (states[state].indexOf(cityName) !== -1) {
return state;
}
})
return false;
}
有很多方法(参见其他答案)所以让我们来看看性能。
首先迭代你的对象 http://jsperf.com/object-keys-vs-for-in-with-closure/3
在我的浏览器中,最快的案例是Object.keys for loop
,所以
getStateByCityName(cityName) {
var statesRaw = sessionStorage.getitem('states');
var states = JSON.parse(statesRaw);
var states_keys = Object.keys(states);
for (var i = 0, l = states_keys.length; i < l; i++) {
// check if city exists
}
return false;
}
接下来,我们需要检查该城市是否存在。我认为有两种方法可以做到:
1)正如其他人建议用for
循环迭代
2)我的建议.indexOf()
http://jsperf.com/js-for-loop-vs-array-indexof/2
在我的浏览器中indexOf()
得到了更好的结果,所以最后的功能
getStateByCityName(cityName) {
var statesRaw = sessionStorage.getitem('states');
var states = JSON.parse(statesRaw);
var states_keys = Object.keys(states);
for (var i = 0, l = states_keys.length; i < l; i++) {
if (states[states_keys[i]].indexOf(cityName) !== -1) {
return states_keys[i];
}
}
return false;
}
正如有人建议使用try/catch
getStateByCityName(cityName) {
var states = {};
try {
states = JSON.parse(sessionStorage.getitem('states'));
} catch (e) {
}
var states_keys = Object.keys(states);
for (var i = 0, l = states_keys.length; i < l; i++) {
if (states[states_keys[i]].indexOf(cityName) !== -1) {
return states_keys[i];
}
}
return false;
}
答案 3 :(得分:0)
这应该有效,但无法测试:
function (arrayTarget, itemToSearch){
for (x in arrayTarget) {
for(y in arrayTarget[x])
if(itemToSearch == arrayTarget[x][y])
return x;
}
}