Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查已存在的本地存储变量,如果不存在,请创建一个新变量_Javascript_Jquery_Html_Local Storage - Fatal编程技术网

Javascript 检查已存在的本地存储变量,如果不存在,请创建一个新变量

Javascript 检查已存在的本地存储变量,如果不存在,请创建一个新变量,javascript,jquery,html,local-storage,Javascript,Jquery,Html,Local Storage,我想通过检查本地存储变量是否已经存在来创建它。如果变量已经存在,请更改变量名称并创建一个新的变量。但我不明白怎么做。请帮我做这个。谢谢 这是我的密码 var vCount=1; var vName='SESSION_'+vCount; while(localStorage.getItem(vName) === null) { vCount++; vName='SESSION_'+vCount; //if variable name available create a ne

我想通过检查本地存储变量是否已经存在来创建它。如果变量已经存在,请更改变量名称并创建一个新的变量。但我不明白怎么做。请帮我做这个。谢谢

这是我的密码

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

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

   //if variable name available create a new variable 
}

从计数开始获取名称,然后查询本地存储以查看其是否存在。如果是-增加计数并将该值保存到贷款存储中。如果不存在-它不存在,请保存原始文件

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);
}
您可以这样做: (我认为您只需要创建一个新的局部变量)


您可以通过使用递归来解决此问题:

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);

这里的断裂条件是什么?何时停止创建新的localStorage变量?这是我的问题,它会导致无限循环。也许我做错了。我必须增加vCount。我想要不同的名称,如SESSION_1、SESSION_2。localStorage只是检查当前浏览器是否支持localStorage(在IE 7、8等旧浏览器中很有用)。
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);