Hello i have problem with javascript for loop, i have 2 items in localStorage:
{"nazev":"1","sire":"2","mnozstvi":"3","barva":"4","typ":"5","slozeni":"6","strec":"7","poznamka":"8"}
{"nazev":"9","sire":"10","mnozstvi":"11","barva":"12","typ":"13","slozeni":"14","strec":"15","poznamka":"16"}
my code:
if(window.localStorage.length > 0) {
for (var i = 0, len = localStorage.length; i < len; i++) {
var foo = localStorage.getItem(localStorage.key(i));
}
//con
$('#nv').html(foo);
}
and html output (console.log is outputting both; but this not):
{"nazev":"9","sire":"10","mnozstvi":"11","barva":"12","typ":"13","slozeni":"14","strec":"15","poznamka":"16"}
if someone know why it's happening and how i can fix it :/
if(window.localStorage.length > 0) {
var foo = '';
for (var i = 0, len = localStorage.length; i < len; i++) {
foo += localStorage.getItem(localStorage.key(i));
}
//con
$('#nv').html(foo);
}
The code is writing the last one as you asked it to, You can accumulate and then print; foo +=
if(window.localStorage.length > 0) {
var foo ='';
for (var i = 0, len = localStorage.length; i < len; i++) {
foo += localStorage.getItem(localStorage.key(i));
}
//con
$('#nv').html(foo);
}
In your code, foo is taking the last value, you need to concatenate it inside for loop. I am assuming you have initialised foo earlier.
if(window.localStorage.length > 0) {
for (var i = 0, len = localStorage.length; i < len; i++) {
var foo+ = localStorage.getItem(localStorage.key(i)); //concate the string
}
$('#nv').html(foo);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.