There are two files. The first:
<div class="someclass">text1</div>
<div class="someclass">text2</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text1","text2"]
The second (files are identical except inner text in first two lines):
<div class="someclass">text3</div>
<div class="someclass">text4</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text3","text4"]
I would like the second file to give ["text1","text2","text3","text4"]
, or maybe ["text3","text4","text1","text2"]
.
How can I do that?
You need to retrieve the previously-stored data (if any), and append to that array. Something like:
var foostr = localStorage.foobar || "[]"; arr = JSON.parse(foostr); var foo = document.getElementsByClassName("someclass"); Array.prototype.forEach.call(foo, function(elem) { arr.push(elem.innerHTML); }); localStorage.foobar = JSON.stringify(arr); alert(localStorage.foobar);
So you need to see if there is anything and concatenate it to the array.
if (localStorage.foobar) {
var prev = JSON.parse(localStorage.foobar);
arr = arr.concat(prev);
}
localStorage.foobar = JSON.stringify(arr);
You can concat the both arrays after retrieving localStorage's contents first, using JSON.parse()
:
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(JSON.parse(localStorage.foobar).concat(arr));
console.log(localStorage.foobar);
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.