繁体   English   中英

将变量从循环存储为数组到localStorage

[英]Store variable from loop as array to localStorage

for循环的结果作为数组存储到localStorage的方式是什么? 也就是说,结果应为: ["./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>

首先,创建href数组。

这使用Array.prototype.map从元素的HTMLCollection创建新的href数组。

var foo = document.getElementsByClassName("someclass");

var arr = Array.prototype.map.call(foo, function(elem) {
    return elem.getAttribute("href");
});

然后使用JSON.stringify()对其进行序列化,然后将其存储在localStorage任何位置。

localStorage.foobar = JSON.stringify(arr);

当然,存储您的数据不需要JSON。 您可以根据需要序列化它。

您可能已经使用.join()来创建一个逗号分隔的字符串。

var foo = document.getElementsByClassName("someclass");

localStorage.foobar = Array.prototype.map.call(foo, function(elem) {
    return elem.getAttribute("href");
}).join(",");

虽然这不是您描述的特定结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM