簡體   English   中英

使用 .find 方法不會從解析的 JSON 返回對象

[英]Using .find method does not return object from parsed JSON

我正在使用 Vue.js 3,但我認為這與我的問題無關。 我正在調用 localStorage 以獲取帖子對象的 JSON 數組,對其進行解析,並使用 id 查找帖子。 我從路由中獲取 id 沒有問題,但使用 .find 搜索解析的數組返回未定義。

post.vue 文件

    created() {
        this.postId = this.$route.params.id;
        console.log("******    POST ID *********");
        console.log(this.postId);

        var posts = JSON.parse(localStorage.getItem("posts"));
        console.log("******    POSTS ARRAY *********");
        console.log(posts);

        this.post = posts.find(post => post.id === this.postId);
        console.log("****** POST *********");
        console.log(this.post);
        
    }

這是控制台日志

this.postId的類型是字符串, posts數組中每個對象的 id 的類型是數字。 所以你可以使用==而不是=== 或者使用parseIntthis.postId的類型this.postId為 number 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM