I am writing a function that will take a variable then check to see if that variable is in localStorage, and if it's not, add it to localStorage. If it is in localStorage, it appends a number to the end, so that a new localStorage key gets added.
So far, I've gotten this far:
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 />");
}
}
That way, when I run the function say 5 times, I should have localStorage keys for:
Test, Test 1, Test 2, Test 3, Test 4
Instead, I have localStorage keys for
Test, Test 1, Test 1 1, Test 1 1 1, Test 1 1 1 1
I'm not sure why the numbers aren't adding, but here's a jsFiddle to demonstrate: http://jsfiddle.net/charlescarver/x6ALG/5/
2 Answers 2
Move the counter to outside the function so that you don't reset it to zero each time you call the function, and keep the title parameter clean so that you can perform arithmetic with the counter.
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 />");
}
}
Note the newTitle variable.
3 Comments
Test, Test 1, Test 2... etc?var newTitle = title; if( counter > 0 ) newTitle += " " + counter;Dont initialize the counter to 0 inside your function test. Make it global and intialize it outside the function. Every time your function is called, it starts the count from 0.
parseIntbefore addingcounteris not a string. It should be a number object, since I'm only adding1to the previous number, which is a number object,0.counterto 0 at the beginning of the function, so it's reset every time you calltest().var counter = 0to the start of the script outside the function. Also, iftitle = title + " " + counter, you're appending a space and the counter number to the existing title, so iftitleis "Test 1" andcounteris 2, you'll get"Test 1" + " " + 2 == "Test 1 2".test()function).