[英]Store variable from loop as array to localStorage
What's the way to store result of the for
loop as array to localStorage? 将
for
循环的结果作为数组存储到localStorage的方式是什么? That is, the result should be: ["./somepage1.html", "./somepage2.html"]
. 也就是说,结果应为:
["./somepage1.html", "./somepage2.html"]
。
<div class="someclass" href="./somepage1.html">foo</div>
<div class="someclass" href="./somepage2.html">foo</div>
<script>
var foo = document.getElementsByClassName("someclass");
for (var i = 0; i < foo.length; i++)
{
var hrefs = foo[i].getAttribute("href");
console.log(hrefs);
}
</script>
First, create the Array of hrefs. 首先,创建href数组。
This uses Array.prototype.map
to create a new Array of hrefs from the HTMLCollection of Elements. 这使用
Array.prototype.map
从元素的HTMLCollection创建新的href数组。
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.getAttribute("href");
});
Then serialize it using JSON.stringify()
, and store it wherever you want in localStorage
. 然后使用
JSON.stringify()
对其进行序列化,然后将其存储在localStorage
任何位置。
localStorage.foobar = JSON.stringify(arr);
Of course, JSON isn't required to store your data. 当然,存储您的数据不需要JSON。 You can serialize it however you want.
您可以根据需要序列化它。
You could have used .join()
instead to create a comma-separated string. 您可能已经使用
.join()
来创建一个逗号分隔的字符串。
var foo = document.getElementsByClassName("someclass");
localStorage.foobar = Array.prototype.map.call(foo, function(elem) {
return elem.getAttribute("href");
}).join(",");
Though this isn't the specific result you described. 虽然这不是您描述的特定结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.