[英]How to access the length of an array within an object within LocalStorage
I am having some troubles with the following: I have an array in an object in localStorage and I need to find the number of elements contained in the array. 我在以下方面遇到了一些麻烦:我在localStorage的对象中有一个数组,我需要查找数组中包含的元素数。
My code is as following 我的代码如下
for (var i = 0; i < localPosts.length; i++){
local_tags = window.localStorage.getItem(localStorage.key(i)).tags
console.log(local_tags);
for (var f = 0; f < local_tags.length; f++) { // <--- error occurs here
tagf = local_tags[f]
console.log(tagf);
for (var j = 0; j < local_tags.length; j++) {
if(tagf == tags[j]){
print_post(i);
}
}
}
}
Please excuse code messiness 请原谅代码混乱
This is an example myh json file(in Json format(this is stringified before it goes into the loops)): 这是一个示例myh json文件(Json格式(在进入循环之前已被字符串化)):
{
"article1": {
"title": "Hello World!",
"desc": "This is the first post on this website!",
"img": "",
"id": 0,
"tags": ["1", "3"]
},
"article2":{
"title": "",
"desc": "",
"img": "",
"id": 1,
"tags": ["1","2"]
}
} }
The problem with this code is whenever I try accsessing the parent function i get an error that goes like this: 这段代码的问题是,每当我尝试访问父函数时,我都会收到如下错误:
Uncaught TypeError: Cannot read property 'length' of undefined
and the log of local_tags returns 并且local_tags的日志返回
undefined
Thanks for the help, I hope I explained it well! 感谢您的帮助,我希望我能解释清楚!
EDIT: made the error more visible in the code 编辑:使错误在代码中更明显
EDIT2: clarified the JSON data is stringified EDIT2:澄清了JSON数据是字符串化的
EDIT3: Added whole Json file EDIT3:添加了整个Json文件
I think the problem is created by tags array 我认为问题是由标签数组造成的
for (var j = 0; j < tags.length; j++) {
if(tagf == tags[j]){
print_post(i);
}
}
it is not defined tags.length 它不是定义的tags.length
Your code has some errors,at line if(tagf == tags[j]){
您的代码在
if(tagf == tags[j]){
Try below code, make some changes as per your requirements 尝试下面的代码,根据您的要求进行一些更改
window.localStorage.setItem("test_article1",JSON.stringify({"article1": { "title": "Hello World!", "desc": "This is the first post on this website!", "img": "", "id": 0, "tags": ["1", "3"]}}))
localPosts = ["test_article1"];
for (var i = 0; i < localPosts.length; i++){
local_tags = JSON.parse(window.localStorage.getItem(localStorage.key(i)))["article1"]["tags"];
console.log(local_tags);
for (var f = 0; f < local_tags.length; f++) { // <--- error occurs here
tagf = local_tags[f]
console.log(tagf);
for (var j = 0; j < local_tags.length; j++) {
console.log(local_tags[j]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.