user606547
user606547

Reputation:

Elements in array ignored by indexOf

I have the following function. Everything works, except for the 'if' statement as noted in the comment.

function markRow(e) {
    var row = e.currentTarget.value ;

    var id, rid, field, color, ico ;

    rid = markedrows.indexOf(row) ;
    if (rid != -1) {
        markedrows.splice(rid, 1) ;
        ico = ICO_FOLDER + ICO_PLUS ;
        color = COLOR_UNMARKED ;
    } else {
        markedrows.push(row) ;
        ico = ICO_FOLDER + ICO_MINUS ;
        color = COLOR_MARKED ;
    }

    e.currentTarget.src = ico ;

    for (var col = 1 ; col <= current.cols() ; col++) {
        alert(col) ;
        alert(markedcols.toString()) ;
        // This 'if' doesn't seem to work
        if (markedcols.indexOf(col) == -1) {
            // This part is ALWAYS executed even when the column is in markedcols
            // I get no error messages in firefox
            id = "r" + row + "c" + col ;
            field = document.getElementById(id) ;
            field.style.background = color ;
        }
    }

    markedrows.sort(numericalorder) ;
}

The alerts are there for debugging and they clearly show that markedcols does contain the column as it should, but the indexOf doesn't seem to catch it.

As I understand it all modern browsers and in particular firefox now supports indexOf on arrays, so I'm completely lost. I've gone through the code's logic over and over and it should work. It just doesn't.

Upvotes: 3

Views: 1371

Answers (1)

pimvdb
pimvdb

Reputation: 154958

I think your problem lies in the fact that:

["1"].indexOf(1) === -1; // true

so you may want .indexOf(col.toString()).

Although "1" == 1, .indexOf seems to do a ===-like comparison. V8 does, at least.

Edit: The specs state that === should be used indeed:

Let same be the result of applying the Strict Equality Comparison Algorithm to searchElement and elementK.

If same is true, return k.

Upvotes: 3

Related Questions