[英]How to give javascript sessionStorage new name with loop
I am trying to make a button, which creates some data and saves it in the sessionStorage. 我试图创建一个按钮,该按钮创建一些数据并将其保存在sessionStorage中。 I want to give every data a key number from 0 and up.
我想给每个数据一个从0开始的键号。 The first time the button is pressed it gets the name/key 0. If the button is then pressed again the name for the new data string/object would be 1 and so on.
第一次按下该按钮时,其名称/键为0。如果再次按下该按钮,则新数据字符串/对象的名称将为1,依此类推。 The thing is that I dont want to overwrite existing data in sessionStorage, so it should check if there is a string/object in the sessionStorage;
事实是我不想覆盖sessionStorage中的现有数据,因此它应该检查sessionStorage中是否有字符串/对象。 if yes give it a new name, if no save it.
如果是,则给它起一个新名称,如果否,则保存它。
In my following code, cpData is the data I want to store in sessionStorage: 在我的以下代码中,cpData是我要存储在sessionStorage中的数据:
for (var index = 0; index <= window.sessionStorage.key(index); index++) {
if (index > window.sessionStorage.key(index)) {
window.sessionStorage.setItem(index, cpData);
break;
}
};
I found out by myself. 我自己发现的。 This code should do it if one is needs the to do the same:
如果需要这样做,则此代码应执行以下操作:
for (var index = 0; index >= window.sessionStorage.key(index); index++) {
if (window.sessionStorage.key(index) === null) {
window.sessionStorage.setItem(index, JSON.stringify(cpData));
break;
} else if (index > window.sessionStorage.key(index)) {
window.sessionStorage.setItem(index, JSON.stringify(cpData));
break;
}
};
This time it checks wether or not window.sessionStorage.key(index)
isn't there. 这次它检查是否
window.sessionStorage.key(index)
不存在。 If so it will create a datastring. 如果是这样,它将创建一个数据字符串。 The
break;
break;
statement stops the loop immediately. 语句立即停止循环。 Now the next time the button is pressed and the loop is started, it can see that there is already a datastring, it will then continue to loop until
index
value is bigger than the key biggest key value at the moment. 现在,下次按下按钮并开始循环时,可以看到已经有一个数据字符串,然后它将继续循环直到
index
值大于当前最大键值为止。 When it is bigger than al previous saved data, it will save the data and break;
当它大于以前保存的数据时,将保存数据并
break;
the loop. 循环。
If one wants to check it by him/herself add this to the same script: 如果要自己检查,请将其添加到同一脚本中:
var i = 0, oJson = {}, sKey;
for (i; sKey = window.sessionStorage.key(i); i++) {
oJson[sKey] = window.sessionStorage.getItem(sKey);
}
console.log(oJson);
This will print out ALL sessionStorage data in console. 这将在控制台中打印出所有sessionStorage数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.