Javascript indexOf() always returns -1

Posted by Thomas on Stack Overflow See other posts from Stack Overflow or by Thomas
Published on 2012-10-16T13:06:31Z Indexed on 2012/10/17 11:01 UTC
Read the original article Hit count: 195

Filed under:

I try to retrieve the index of en element in an array.

This works perfectly

        var onCreate = function (event) {
        console.assert(markers[markerId] === undefined);

        var markerId = event.markerId;
        markers[markerId] = {};

        var marker = markers[markerId];
        // create the container object
        marker.object3d = new THREE.Object3D();
        marker.object3d.matrixAutoUpdate = false;
        scene.add(marker.object3d);

        //UPDATE ARRAY HOLDING CURRENT MARKERS
        console.log("ON CREATE");
        console.log("current detected markers: " + currentMarkers);
        var idx = currentMarkers.indexOf(markerId); // Find the index
        console.log("marker " + event.markerId + " has index: " + idx);
        if(idx==-1) // if does not exist
            currentMarkers.push(markerId);

But this doesnt...

    var onDelete = function (event) {

        console.assert(markers[event.markerId] !== undefined);
        var markerId = event.markerId;
        //UPDATE ARRAY HOLDING CURRENT MARKERS
        console.log("ON DELETE");
        console.log("current detected markers: " + currentMarkers);
        var idxx = currentMarkers.indexOf(markerId); // Find the index
        console.log("marker " + markerId + " has index: " + idxx);
        if(idxx != -1) {// if DOES exist
            currentMarkers.splice(idxx, 1); //Delete
            var idxxx = currentMarkersCoverChecked.indexOf(markerId); // Find the index
            if(idxxx == -1) // if does NOT exist, so if not being checked
                checkMarkerCovered(markerId);
        }
        onDeleteRandom(markerId);
        var marker = markers[markerId];
        scene.remove(marker.object3d);
        delete markers[markerId];

Look at my console output:

ON CREATE 
current detected markers: 2,1,4 
marker 3 has index: -1 
ON CREATE main.js:266
current detected markers: 2,1,4,3 
marker 4 has index: 2 
ON DELETE 
current detected markers: 2,1,4,3
marker 2 has index: -1 
ON CREATE 
current detected markers: 2,1,4,3 
marker 2 has index: 0 
ON DELETE 
current detected markers: 2,1,4,3 
marker 1 has index: -1 

© Stack Overflow or respective owner

Related posts about JavaScript