当我尝试将JSON.parse与内部存储中的数据一起使用时,我和我的同学收到以下错误消息。该代码是由我们的讲师提供给我们的,因此不确定是什么问题。

内部存储器不包含任何内容,并以0初始化“ pageViews”,或者如果内部存储器中有数据,则它应该是一个数组。


  Uncaught SyntaxError:JSON中位于位置1的意外令牌o
  HTMLDocument.addPageView上的JSON.parse()


这是我们的代码。

const pageViewsKeyName = "pageViews";

function addPageView() {

    let pageViews = localStorage.getItem(pageViewsKeyName);
    let arr = [];
    if (pageViews && pageViews.length > 0) {
        // get the array stored in local storage at pageViewsKeyName
        arr = JSON.parse(pageViews);

        // now we're able to insert an item in the page view data
        let newPageData = {
            "path": window.location.pathname,
            "timestamp": moment()
        };

        // now add new page data to the array
        arr.push(newPageData);

        // finally, we want to update our storage with the most up to date array
        localStorage.setItem(pageViewsKeyName, arr);
    }
}

最佳答案

JSON.parse用于将字符串JSON值解析为JSON对象。看起来pageViews已经包含JSON对象。因此,您无需解析它。您可以console.log(pageViews)确认。

关于javascript - 尝试从内部存储数据中使用JSON.parse时收到错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59168373/

10-11 23:14
查看更多