1

I'm saving a list of images (from a gallery) to a device using LocalStorage. I've solved the problem for the most part - getting data in and out, and populating an HTML list of items that are in there. Easy.

I'm now trying to put a check in to look at the item being saved, check all the values in the database, and only add it if it isn't a duplicate. As I'm building this I'm getting deeper and deeper in a hole and am at the point where I need a bit of help.

Here's my function at the moment:

function storeFavourite(currentImage) {
for (var i=0; i < localStorage.length; i++) {
    item = localStorage.getItem('fav'+i);
    if (item = currentImage) {
        console.log('fav'+i+', '+currentImage+' in db already');
    } else {
        next = localStorage.length;
        localStorage.setItem('fav'+next, currentImage);
        console.log('fav'+next+', '+currentImage);
        updateFavouritesList(); 
    }
}
}

It's a big mess and I've completely confused myself. Can anyone help me figure it out?

I'm not at all opposed to reformatting the data structure if needed. At the moment the keys are fav0, fav1 and so on.

The updateFavouritesList() function used there just iterates over the localStorage database and creates <li> items from it to add to a list.

adnrw
  • 1,038
  • 6
  • 13

1 Answers1

1

You have an error in the line:

if (item = currentImage) {

You're assigning item. If item isn't null/empty/zero/falsy, then it will always resolve as true. Perhaps it should be:

if (item == currentImage) {

or even:

if (item === currentImage) {

depending on which type currentImage is.

EDIT: In any case, here is a function which will do what you're looking for:

function storeFavourite(item) {
    for (var i in localStorage) {
        if (localStorage[i] === item) return;
    }
    localStorage["fav" + localStorage.length] = item;
}
Stoive
  • 11,232
  • 4
  • 24
  • 32
  • I tried assigning different operators but it didn't make much of a difference (just started returning false instead of true and vice versa). Your solution worked perfectly, thank you. – adnrw Mar 16 '12 at 03:02
  • No problems. If the operators don't make much sense, it's worth learning more about expression evaluation, and 'truthy' and 'falsy'. `a = b` evaluates to whatever `b` is (hence why `a = (b = c)` will cause `a` to be assigned the value of `c`). Added to that, if `c` is not `null`, `undefined`, `0`, `false`, `NaN` or `""`, it'll be converted to `true` when a boolean is needed. – Stoive Mar 16 '12 at 03:48