使用 .find 方法不会从解析的 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);

        

    }

qq_笑_17
浏览 132回答 1
1回答

12345678_0001

类型this.postId为字符串,数组中每个对象的id类型posts为数字。所以你可以使用==代替===. 或者使用 将 的类型更改this.postId为数字parseInt。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript