2016-11-13 32 views
-3

我想通過檢查已存在與否來創建本地存儲變量。如果變量已經存在,則更改變量名稱並創建一個新變量。但我無法理解如何去做。請幫我解決一下這個。由於檢查本地存儲變量是否已存在,如果沒有創建新變量

這裏是我的代碼

var vCount=1; 
var vName='SESSION_'+vCount; 
while(localStorage.getItem(vName) === null) 
{ 

    vCount++; 
    vName='SESSION_'+vCount; 

    //if variable name available create a new variable 
} 
+0

什麼這裏是休息狀態嗎?你什麼時候想停止創建新的localStorage變量? – Nitesh

+0

這是我的問題,它導致無限循環。也許我做錯了。 –

回答

0

開始與計數得到的名稱,然後查詢本地存儲,看它是否存在。如果是這樣 - 增加計數並將該值保存到貸款存儲。如果沒有 - 它不存在,所以保存原件。

var vCount=1; 
var vName='SESSION_'+vCount; 

var storedName= sessionStorage.getItem("vName"); 
if (storedName){ 
    var vCount += 1; 
    var vName='SESSION_' + vCount; 
    localStorage.setItem(vName, vName); 
    //this will increment the number and set that as the variable name 
} else { 
    localStorage.setItem("vName", vName); 
} 
+0

必須增加vCount。我需要分別名爲SESSION_1,SESSION_2這樣的名字。 –

+0

是 - 只是意識到 - 嘗試更新的答案 – gavgrif

0

你可以這樣做: (我正在考慮你只是想創建一個新的局部變量)

var vCount=1; 
var vName='SESSION_'+vCount; 
while(true && localStorage) 
{ 
    //if variable name not available create a new variable 
    if(!localStorage.getItem(vName)){ 
    localStorage.setItem(vName,"your value"); 
    break; 
    } 
    vCount++; 
    vName='SESSION_'+vCount; 
} 
+0

你能清楚我什麼是真的&localStorage –

+0

localStorage只是用來檢查你當前的瀏覽器是否支持localStorage或不適用於像IE 7,8這樣的舊瀏覽器。 – Nitesh

0

您可以通過使用遞歸解決這個問題:

var vCount=1; 
function storeVariable(valueToStore){  
    var vName='SESSION_'+vCount; 
    if(localStorage.getItem(vName) === null){ 
     vCount++; 
     vName='SESSION_'+vCount; 

     //if variable name available create a new variable 
    }else{ 
     storeVariable(valueToStore); 
    } 
} 

//you can reset vCount = 1 before calling this function, if you need to start the counter over again. 
storeVariable(valueToStore);