array.splice在javascript中无法正常工作

scr*_*rd3 0 javascript arrays splice

我正在编写一个简单的数独求解器,它采用数字1-9的数组,并且如果它们不可能用于该单元格则将它们设置为空.一个例子是一个单元格,其中答案只能是5,所以所有数字都设置为null,除了5.然后,我有一个clean()函数,它删除数组中的所有值为null,但这是无法正常工作.原始数组就是这个.

[null,null,null,null,5,null,null,null,null]
Run Code Online (Sandbox Code Playgroud)

清洁后,它返回

[null,null,5,null,null]
Run Code Online (Sandbox Code Playgroud)

javascript代码在这里,网格是数独中的数字网格

function mainmethod(){

        var onepos=oneposs();

    }
    function oneposs(){

        var possibs=new Array(1,2,3,4,5,6,7,8,9);
        for (var ycount=0;ycount<=8;ycount++){
            var value=grid[0][ycount];
            var index=possibs.indexOf(value);
            possibs[index]=null;

        }
    //      for(var xcount=0;xcount<=8;xcount++){
    //      var value=grid[xcount][0];
    //      var index=possibs.indexOf(value);
    //      possibs.splice(index,1);
    //  }

        possibs=clean(possibs);
        alert(JSON.stringify(possibs));
    }
    function clean(array){
        for(var i=0;i<=8;i++){
            if(array[i]===null){
                array.splice(i,1);
            }
        }
        return array;
    }
Run Code Online (Sandbox Code Playgroud)

从本质上讲,array.splice并没有拼接所需的一切,我不知道为什么

Bal*_*alo 6

您在迭代时更改数组.尝试类似的东西:

function clean(array){
    for(var i=0;i<=8;i++){
        if(array[i]===null){
            array.splice(i--,1);
        }
    }
    return array;
}
Run Code Online (Sandbox Code Playgroud)

--较低的指标,因为下一个项目后会有比你删除的项目相同的指数.

此外,作为参数传递的对象和数组通过引用传递,因此您不需要返回任何内容.你可以做clean(possibs);