2017-01-28 6 views
0

要素をisntクッキーと比較したいと思います。 私はスクリプトを作成しました(コンソールでのみ使用しています) - 動作していますが、1つ目のクッキーをチェックして、2番目のクッキーを追加しています。私が例えばクッキー2を持っている - test1、test2は動作していません。どのように私はそれを変更することができますか?配列をチェックし、javascriptで新しいクッキーを追加する方法

var arrMy = ["test1", "test2", "test3", "test4", "test5"]; 
var i = 0; 
function nextItem() { 
    i = i + 1;/
    i = i % arrMy.length; 
    return arrMy[i]; 
} 
var x = nextItem(); 
console.log(x); 

for(document.cookie.indexOf(x) > -1 == true;;){ 
function nextItem2() { 
    i = i + 1; 
    i = i % arrMy.length; 
    return arrMy[i]; 
} 

var w = nextItem2(); 
if(x != w){ 
break; 
} 
} 
document.cookie = w+'=yet another test; expires=Fri, 27 Jul 2021 02:47:11 UTC; path=/' 
+0

は、なぜあなたは同じことを行う2つの機能が必要なのでしょうか? –

+0

配列から選択された要素が既存のクッキーである場合、配列から次の要素を選択したいとします。その要素が最初の結果と異なる場合は、次のクッキーを作成します...そのようなものは、私はjsで初心者です – Mkrasek

答えて

0
//get the cookies: 
var cookies=document.cookie.split(";"); 
//cookies to add 
var add=["test=1","test=2"] 
//loop trough the cookies to add 
add.forEach(cookie=>{ 
     //if the cookie isnt found 
     if(!cookies.find(el=>el.split("=")[0]===cookie.split("=")[0])){ 
      //add the cookie 
      cookies.push(cookie);  
     } 
}); 
document.cookie=cookies.join(";"); 
関連する問題