indexOf忽略了数组中的元素

Elements in array ignored by indexOf

本文关键字:元素 数组 indexOf      更新时间:2023-09-26

我有以下函数。除了评论中提到的"if"语句外,一切都正常。

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) ;
}

alert是用来调试的,它们清楚地表明markedcols确实包含了它应该包含的列,但indexOf似乎没有捕捉到它

据我所知,所有现代浏览器,尤其是firefox,现在都支持数组上的indexOf,所以我完全迷失了方向。我已经一遍又一遍地研究了代码的逻辑,它应该有效。只是没有。

我认为你的问题在于:

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

所以你可能想要.indexOf(col.toString())

尽管"1" == 1.indexOf似乎做了类似===的比较。V8至少做到了。

编辑:规范规定确实应该使用===

same是将严格相等比较算法应用于searchElementelementK的结果。

如果sametrue,则返回k