Javascript indexOf()总是返回-1

时间:2012-10-16 13:06:31

标签: javascript

我尝试检索数组中en元素的索引。

这完美无缺

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

但这不......

    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];

查看我的控制台输出:

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 

2 个答案:

答案 0 :(得分:1)

您是否已在markerId

中检查了值的类型

JavaScript Array允许您将Integer类型以及String类型和Object类型插入Array。如果某个值属于Integer类型,并且您尝试indexOf("stringvalue");,则可能会获得-1 as return value

希望这可以帮助您解决问题!

答案 1 :(得分:0)

第二个示例不起作用,因为currentMarkersCoverChecked未定义。