我正在编写一个函数,它将获取一个变量,然后检查该变量是否在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/
答案 0 :(得分:1)
将计数器移动到函数外部,这样每次调用函数时都不会将其重置为零,并保持title
参数清洁,以便您可以对计数器执行算术运算。
var counter = 0;
var title = "Test";
test(title);
function test(title) {
var newTitle = title + " " + counter;
console.log("counter = " + counter);
if (localStorage.getItem( newTitle )) {
counter = counter + 1;
console.log("found " + newTitle);
console.log("found " + counter);
test(title);
} else {
console.log("not found " + newTitle);
console.log("not found " + counter);
localStorage.setItem( newTitle, " " );
load();
}
}
function load() {
for (var key in localStorage) {
$(".keys").append(key + "<br />");
}
}
请注意newTitle
变量。
答案 1 :(得分:0)
在功能测试中不要将计数器初始化为0。使其全局并在函数之外初始化它。每次调用函数时,它都会从0开始计数。