如何将存储在本地存储中的所有数组元素打印到屏幕上

huangapple go评论88阅读模式
英文:

How to print to screen all array elements stored in local storage

问题

Good Morning,
I'm new in javascript and I'm having trouble getting a full array from local storage.
I made this code, but it only prints on screen the data stored in the last element of the array, and I intended to print on screen the data of all elements of the array. Someone can help me?
I can't use jquery

var preco_final=0; // preço total -> adiciona o preco de todos os bilhetes comprados
function mostrar(){  

    var carrinho=JSON.parse(localStorage.getItem('carrinho-compras'));
    for(i=0;i<carrinho.length;i++)
    {    

        //guarda em vari&#225;veis os dados que est&#227;o no localstorage
        var tipo_bilhete_carrinho= "tipo de bilhete: " +carrinho[i].tipo_de_bilhete;
        var dias_carrinho="dias: "+carrinho[i].dias;
        var nome_carrinho="nome: "+carrinho[i].nome_t;
        var nadultos_carrinho="n&#250;meor de adultos: "+carrinho[i].numero_adultos;
        var ncriancas_carrinho="n&#250;mero de crian&#231;as: "+carrinho[i].numero_criancas;
        var preco_carrinho="pre&#231;o do bilhete: "+carrinho[i].preco_total; // pre&#231;o do bilhete em causa
        preco_final +=carrinho[i].preco_total; // pre&#231;o total -&gt; adiciona o preco de todos os bilhetes comprados

        // Guarda todas as vari&#225;veis num array e converte numa lista pela fun&#231;&#227;o map
        var compra=[tipo_bilhete_carrinho,dias_carrinho,nome_carrinho,nadultos_carrinho,ncriancas_carrinho,preco_carrinho];
        ReactDOM.render(React.createElement("ul", {id:"lista_compras"},
            compra.map( (compra) => React.createElement("li", null, compra)),React.createElement("hr",null,"")),document.getElementsByClassName("itens")[0]);
        //hr tag que define mudan&#231;a tem&#225;tica -&gt; adiciona uma linha  
    }
    document.getElementById('preco_total').innerHTML= "Pre&#231;o total: "+preco_final;
}

function apagar(){
    localStorage.removeItem('carrinho-compras'); //apaga o carrinho de compras
    document.getElementsByClassName('itens')[0].innerHTML="";
    document.getElementById('preco_total').innerHTML= "";
}

How do I store data in local storage:

// Pega a lista j&#225; registada, se n&#227;o houver cria
var carrinho_de_compras = JSON.parse(localStorage.getItem('carrinho-compras') || '[]');
// Adiciona reserva
carrinho_de_compras.push({
 tipo_de_bilhete: tipo_bilhete,
 dias: ndias,
 nome_t:nome,
 numero_adultos: nadultos,
 numero_criancas: ncriancas,
 preco_total: precoTotal
});
// Salva a lista alterada
localStorage.setItem("carrinho-compras", JSON.stringify(carrinho_de_compras));
alert("Bilhete adicionado ao carrino de compras");
英文:

Good Morning,
I'm new in javascript and I'm having trouble getting a full array from local storage.
I made this code, but it only prints on screen the data stored in the last element of the array, and I intended to print on screen the data of all elements of the array. Someone can help me?
I can't use jquery

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var preco_final=0; // pre&#231;o total -&gt; adiciona o preco de todos os bilhetes comprados
function mostrar(){  
var carrinho=JSON.parse(localStorage.getItem(&#39;carrinho-compras&#39;));
for(i=0;i&lt;carrinho.length;i++)
{    
//guarda em vari&#225;veis os dados que est&#227;o no localstorage
var tipo_bilhete_carrinho= &quot;tipo de bilhete: &quot; +carrinho[i].tipo_de_bilhete;
var dias_carrinho=&quot;dias: &quot;+carrinho[i].dias;
var nome_carrinho=&quot;nome: &quot;+carrinho[i].nome_t;
var nadultos_carrinho=&quot;n&#250;meor de adultos: &quot;+carrinho[i].numero_adultos;
var ncriancas_carrinho=&quot;n&#250;mero de crian&#231;as: &quot;+carrinho[i].numero_criancas;
var preco_carrinho=&quot;pre&#231;o do bilhete: &quot;+carrinho[i].preco_total; // pre&#231;o do bilhete em causa
preco_final +=carrinho[i].preco_total; // pre&#231;o total -&gt; adiciona o preco de todos os bilhetes comprados
// Guarda todas as vari&#225;veis num array e converte numa lista pela fun&#231;&#227;o map
var compra=[tipo_bilhete_carrinho,dias_carrinho,nome_carrinho,nadultos_carrinho,ncriancas_carrinho,preco_carrinho];
ReactDOM.render(React.createElement(&quot;ul&quot;, {id:&quot;lista_compras&quot;},
compra.map( (compra) =&gt; React.createElement(&quot;li&quot;, null, compra)),React.createElement(&quot;hr&quot;,null,&quot;&quot;)),document.getElementsByClassName(&quot;itens&quot;)[0]);
//hr tag que define mudan&#231;a tem&#225;tica -&gt; adiciona uma linha  
}
document.getElementById(&#39;preco_total&#39;).innerHTML= &quot;Pre&#231;o total: &quot;+preco_final;
}
function apagar(){
localStorage.removeItem(&#39;carrinho-compras&#39;); //apaga o carrinho de compras
document.getElementsByClassName(&#39;itens&#39;)[0].innerHTML=&quot;&quot;;// apaga o conteudo da div, de modo a n&#227;o mostrar nada no ecr&#227;
document.getElementById(&#39;preco_total&#39;).innerHTML= &quot;&quot;; // apaga o conteudo da div do pre&#231;o total
}

<!-- language: lang-css -->

body{ margin: 0;}
#lista_compras{
list-style-type: none;     /* Remove as bolinhas dos elementos da lista */
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;pt&quot;&gt;
&lt;head&gt;  
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/carrinho_compras.css&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/menu.css&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/cabecalho_rodape.css&quot;&gt;
&lt;script src=&quot;js/react.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/react-dom.js&quot;&gt;&lt;/script&gt;
&lt;link rel=&quot;icon&quot; type=&quot;images/jpg&quot; href=&quot;imagens/logo.jpg&quot;&gt; 
&lt;title&gt;Adventure Park - Bilheteira&lt;/title&gt;
&lt;/head&gt;
&lt;body onload=&quot;mostrar()&quot;&gt;
&lt;header id=&quot;cabecalho&quot;&gt;    &lt;!-- Cabe&#231;alho / menu--&gt;
&lt;a href=&quot;index.html&quot; id=&quot;hyper_to_home&quot;&gt;
&lt;div id=&quot;logo_name&quot;&gt;
&lt;img id=&quot;logo&quot; src=&quot;imagens/logo.png&quot;&gt;
&lt;h3 id=&quot;nome_parque&quot;&gt;Parque de divers&#245;es&lt;/h3&gt;
&lt;/div&gt;
&lt;/a&gt;
&lt;div id=&quot;menudiv&quot;&gt;&lt;/div&gt;
&lt;picture&gt;&lt;a href=&quot;carrinho_de_compras.html&quot;&gt;&lt;img id=&quot;carrinho_de_compras&quot;src=&quot;imagens/Bilheteira/carrinho_compras.png&quot; width=&quot;40px&quot; height=&quot;35px&quot; &gt;&lt;/a&gt; &lt;/picture&gt;
&lt;/header&gt;
&lt;div class=&quot;itens&quot; id=&quot;item&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;preco_total&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;btn_carrinho&quot;&gt;
&lt;a href=&quot;bilheteira.html&quot;&gt;&lt;button&gt;Continuar a comprar&lt;/button&gt;&lt;/a&gt;
&lt;input type=&quot;reset&quot; value=&quot;Apagar itens do carrinho&quot; onclick=&quot;apagar()&quot;&gt;
&lt;/div&gt;
&lt;footer id=&quot;rodape&quot;&gt;      &lt;!-- Rodap&#233; --&gt;
&lt;div id=&quot;data-hora&quot;&gt;12/10/2019 23:59:10&lt;/div&gt;
&lt;/footer&gt;
&lt;script src=&quot;js/menu.js&quot;&gt;&lt;/script&gt; &lt;!-- script do menu --&gt;
&lt;script src=&quot;js/carrinho_compras.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;js/data_e_hora.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;       

<!-- end snippet -->

How do I store data in local storage:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    // Pega a lista j&#225; registada, se n&#227;o houver cria
var carrinho_de_compras = JSON.parse(localStorage.getItem(&#39;carrinho-compras&#39;) || &#39;[]&#39;);
// Adiciona reserva
carrinho_de_compras.push({
tipo_de_bilhete: tipo_bilhete,
dias: ndias,
nome_t:nome,
numero_adultos: nadultos,
numero_criancas: ncriancas,
preco_total: precoTotal
});
// Salva a lista alterada
localStorage.setItem(&quot;carrinho-compras&quot;, JSON.stringify(carrinho_de_compras));
alert(&quot;Bilhete adicionado ao carrino de compras&quot;);

<!-- end snippet -->

答案1

得分: 3

你可以迭代地遍历 localStorage 数组,然后像下面这样逐个打印每个项:

for (var i = 0; i < localStorage.length; i++){
    console.log(localStorage.getItem(localStorage.key(i)));
}
英文:

You can go through the localStorage Array iteratively and then print each item individually like below

for (var i = 0; i &lt; localStorage.length; i++){
console.log(localStorage.getItem(localStorage.key(i)));
}

答案2

得分: 0

我建议添加Mustache.js。它是一个无逻辑*(*没有if和else,也没有循环)的模板引擎,非常容易实现。然后,您可以将其打印到类似showtext组件的地方,例如Showtext.jsx,或者如果您需要弹出Alert类型的组件,我建议使用Reactstrap-modal。如果您需要逻辑模板,随时可以添加Handlebars.js插件到Mustache.js,它是完全兼容的。

英文:

I would suggest to add Mustache.js. Its a logicless* (*no ifs and elses, for cycles) engine to print templates, its super easy to implement. You can then print it into kind of a showtext component, exmp. Showtext.jsx, or if you require pop up, Alert type component, I would suggest Reactstrap-modal. If you will require logic templates, you can at any point add Handlebars.js addon to Mustache.js, its fully compatible.

huangapple
  • 本文由 发表于 2020年1月6日 19:29:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定