2016-08-07 121 views
0

我有一个功能正常的代码,将类元素的标题添加到数组中,然后将其推送到localStorage“数据库”。一切都很好,但我不想多次推送元素“如果它已经存在”。尝试了几个解决方案,但没有完全得到它。任何帮助,高度赞赏。大脑正在融化......,避免将重复项推送到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

我认为你是过度的。 这难道不是只是工作:

if ((x == null) || (x == "") || stores.indexOf(x) > -1) { 
+0

过度这是我的典型:)但发现问题。这是我定义早些时候调试var stores = [C]而不是空的。 (其中C = localStorage数据库,但是,谢谢!现在可以指定 –

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')) 
+0

吗?也许是一个例子吗? –

+0

刚刚编辑我的答案@Mik_A – Hunter

+0

好的我看着这个。 –