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/
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).