我想通过检查已存在或不存在来创建本地存储变量。如果变量已存在,请更改变量名称并创建一个新变量名称。但我无法理解如何做到这一点。请帮我解决一下这个。感谢
这是我的代码
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 :(得分: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);
}
答案 1 :(得分: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;
}
答案 2 :(得分: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);