[英]How can I test for localStorage value in this example?
when I do localStorage.getItem('user');
当我执行
localStorage.getItem('user');
I receive this as value: 我收到此作为值:
{
"userDetails": {
"gender": "",
"language": "de",
"color":
}
}
I need to match my logic according to the language
value. 我需要根据
language
值来匹配我的逻辑。 For example if "language": "de"
do something, if "language": "en"
do something else. 例如,如果
"language": "de"
做某事,如果"language": "en"
做其他事。
How can I match the value in key in my example? 如何在示例中匹配key中的值?
Thanks. 谢谢。
getItem
will return a string , so the first thing to do is parse it: getItem
将返回一个字符串 ,所以首先要做的就是解析它:
var data = JSON.parse(localStorage.getItem("user"));
Assuming your data is valid JSON (the text in the question isn't but looks like it's meant to be, it's missing a value for "color":
), that will return the parsed data. 假设您的数据是有效的JSON(问题中的文本不是,但看起来像是正确的,它缺少
"color":
的值),它将返回已解析的数据。
Now you have an object with a property called userDetails
which, in turn, has a property called language
, so you can access it via data.userDetails.language
, perhaps in a switch
: 现在,您有了一个带有名为
userDetails
的属性的对象,该对象又具有一个名为language
的属性,因此您可以通过data.userDetails.language
,也许在一个switch
:
switch (data.userDetails.language) {
case "de":
// ...
break;
case "en":
// ...
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.