我正在编写一个函数,它将接受一个变量,然后检查该变量是否在 localStorage 中,如果不是,将其添加到 localStorage。如果它在 localStorage 中,它会在末尾附加一个数字,以便添加一个新的 localStorage 键。
到目前为止,我已经做到了这一点:
var title = "Test";
test(title);
function test(title) {
counter = 0;
console.log("counter = " + counter);
if (localStorage.getItem(title)) {
counter = counter + 1;
title = title + " " + counter;
console.log("found " + title);
console.log("found " + counter);
test(title);
} else {
console.log("not found " + title);
console.log("not found " + counter);
localStorage.setItem(title, " ");
load();
}
}
function load() {
for (var key in localStorage) {
$(".keys").append(key + "<br />");
}
}
这样,当我运行该函数 5 次时,我应该有 localStorage 键:
Test, Test 1, Test 2, Test 3, Test 4
相反,我有 localStorage 密钥
Test, Test 1, Test 1 1, Test 1 1 1, Test 1 1 1 1
我不确定为什么没有添加数字,但这里有一个 jsFiddle 来演示:http: //jsfiddle.net/charlescarver/x6ALG/5/