我有一个正常运行的代码,它将类元素的标题添加到数组中,然后将其推送到localStorage“数据库”。一切都很好,但我不想在那里多次推送元素“如果它已经存在”。尝试了几个解决方案,但没有得到它。任何帮助都非常感谢。大脑正在融化..,
var stores=[]
jQuery('.additem').click(function() {
var x = jQuery(this).closest('h4.title').text();
if ((x == null) || (x == "") || (x == ($.inArray(this.x) > -1))) {
jQuery(this).closest('.infobox').html('Already there or empty.');
jQuery(this).closest('.infobox').show().delay(500).fadeOut(1000);
} else {
stores.push(x);
console.log(stores);
window.localStorage.setItem("database", stores.join(" + "));
}
});
还尝试了
(x == (stores.indexOf(this) > -1))
还有其他一些东西。 感谢
答案 0 :(得分:0)
我认为你过度了。 这不正常工作:
if ((x == null) || (x == "") || stores.indexOf(x) > -1) {
答案 1 :(得分:0)
您可以使用Set
可以转换为数组以及从数组进行存储。
var s = new Set();
s.add(value);
localStorage.setItem('mySet',Array.from(s).toString())
var s = new Set(JSON.parse(localStorage.getItem('mySet'))