0

我正在编写一个函数,它将接受一个变量,然后检查该变量是否在 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/

4

2 回答 2

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变量。

演示:http: //jsfiddle.net/x6ALG/7/

于 2013-03-18T19:01:15.290 回答
0

不要在函数测试中将计数器初始化为 0。使其成为全局并在函数外部初始化它。每次调用您的函数时,它都会从 0 开始计数。

于 2013-03-18T18:56:54.873 回答