LocalStorage中实际值之前的“undefined”

时间:2016-02-11 15:13:43

标签: javascript local-storage undefined

这是我使用的代码:

localStorage["FSS"] += JSON.stringify(favSongs);
localStorage["FSTS"] += JSON.stringify(favSongTitle);
localStorage["FIS"] += JSON.stringify(favImages);

但是当我检索到这些值时,我得到了这个:

FSSundefined["0t0FGyhB6C8"]

FSTSundefined["SONIC SYNDICATE - Denied (OFFICIAL MUSIC VIDEO)"]

FISundefined["https://i.ytimg.com/vi/0t0FGyhB6C8/mqdefault.jpg"]

enter image description here

我不明白undefined的来源和位置以及我如何删除它以在屏幕上记录结果(现在当我记录它时也显示undefined)。

1 个答案:

答案 0 :(得分:3)

undefined已经是localStorage中的内容:

document.getElementById('existing').textContent = localStorage[Math.random().toString()];

因为您使用foo += bar语法,脚本将:

  1. 获取foo
  2. 的现有值
  3. 执行类型强制以使foobar兼容
  4. bar附加到现有值
  5. 将组合值分配回foo
  6. 如果foo已包含undefined ...

    这似乎是通过地图访问器访问localStorage属性的工件。如果您使用the getItem method,则会收到null而不是undefined

    由于您正在使用JSON,即使您已有值,简单的字符串连接(字符串+=)也不会起作用。您最终会得到['foo-album']['bar-album'],这是无效的。我建议将现有项目添加为空数组,附加新项目,然后替换存储的值:

    var prev = localStorage.getItem('FSS') || '[]'; // get the existing value or the string representing an empty array
    var data = JSON.parse(prev); // parse into an object
    data.push('New Album');
    localStorage.setItem('FSS', JSON.stringify(data)); // convert back to JSON and set