localStorage returns 未定义但适用于控制台

localStorage returns as undefined but works with console

我写了一个 JavaScript 文件,它从 localStorage 读取历史记录并将其记录到控制台。键 history 的值是一个字符串数组,看起来像这样:

[
  {
    "dateCreated": 1624953025609,
    "link": "localhost/97a4",
    "uri": "google.com"
  }
]

正如预期的那样,key/value 也出现在 Application DevTools 选项卡中。我也可以在 JSON.parse() 之后访问控制台中的数组,如下所示:

JSON.parse(localStorage.getItem("history"))[0].dateCreated;
// 1624953025609

。 然而,另一个 JS 文件看起来像

function checkLocalStorage() {
    if (typeof localStorage !== 'undefined') {
        try {
            localStorage.setItem('feature_test', 'yes');
            if (localStorage.getItem('feature_test') === 'yes') {
                localStorage.removeItem('feature_test');
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    } else {
        return false;
    }
}

var isEnabledLocalStorage = checkLocalStorage();

if (!isEnabledLocalStorage) {
    $('<p></p>').append("Your browser doesn't support <b>localStorage</b> or it is disabled.<br><b>localStorage</b> is required to view your history.")
} else {
    var history = JSON.parse(localStorage.getItem("history"))[0];
    document.write(history.dateCreated);
}

undefined 写入文档。如何从 history localStorage 键获取嵌套对象的值?

它是 undefined,因为在您的 else 语句中,您调用变量 history,但它已经存在:window.history
因此,它没有保存已解析的 JSON,而是无法覆盖,当您检索 dateCreated 属性 时,它不存在于 window.history.

只需将您的变量重命名为 saved_history