如何在html for循环中打印localStorage数组?

时间:2018-04-25 08:34:25

标签: javascript arrays json local-storage

我的localStorage中有一个数组,其中包含[" January"," Febuary"] 我希望它以HTML显示,最好是这样:

Month
January
Febuary

所以我尝试了这段代码:

function show(){
    for(let i = 0;i < localStorage.length;i++){
        var date = JSON.parse(localStorage.getItem("date"));
        }
    for(var b = 0; b < nameLength; b++){
        document.getElementById('storageOut').innerHTML = date[b];
        console.log(date[b]);   
    }   
}

上面的代码确实有效,行"document.getElementById('storageOut').innerHTML = date[b];"只打印出数组中的最后一个数据,但是当我检查控制台时,它会打印出来。

2 个答案:

答案 0 :(得分:0)

您在第一个for循环中创建变量date,并在每次迭代时将其分配给一个值。最简单的方法可能是在单个for循环中进行:

function show(){
  for(let i = 0;i < localStorage.length;i++){
    var date = JSON.parse(localStorage.getItem("date"));
    document.getElementById('storageOut').innerHTML = date;
  }
}

虽然,如果您想要所有日期,您应该将它附加到innerHtml:

...innerHTML += date;

或者更确切地说:

...innerText += date;

答案 1 :(得分:0)

假设您的内容存储在名为数据的本地存储密钥中。请尝试以下方法。

const data = JSON.parse(localStorage.getItem('data'))
data.forEach(item => {
    document.getElementById('storageOut').innerHTML += item
})
相关问题