代码之家  ›  专栏  ›  技术社区  ›  Стёпа Кашкаров

如何访问LocalStorage中对象内的数组长度

  •  1
  • Стёпа Кашкаров  · 技术社区  · 7 年前

    我在以下方面遇到了一些问题: 我在localStorage中的一个对象中有一个数组,我需要找到数组中包含的元素数。

    我的代码如下

    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);
                    }
                }
            }
        }
    

    请原谅代码混乱

    这是一个示例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"]
    }
    

    }

    此代码的问题是,每当我尝试访问父函数时,都会出现如下错误:

    Uncaught TypeError: Cannot read property 'length' of undefined
    

    并返回local\u标记的日志

    undefined
    

    谢谢你的帮助,我希望我能解释清楚!

    编辑:使错误在代码中更可见

    EDIT2:澄清JSON数据已字符串化

    EDIT3:添加了整个Json文件

    2 回复  |  直到 7 年前
        1
  •  0
  •   Alpesh Jikadra    7 年前

    您的代码在第行有一些错误 if(tagf == tags[j]){

    尝试以下代码,根据您的要求进行一些更改

    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]);
                }
            }
        }
    
        2
  •  0
  •   hazrat    7 年前

    我认为问题是由标签数组造成的

    for (var j = 0; j < tags.length; j++) {
       if(tagf == tags[j]){
          print_post(i);
       }
    }
    

    未定义标记。长