简体   繁体   English

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

[英]array.splice not working correctly in javascript

I'm writing a simple sudoku solver, which takes an array of numbers 1-9 and sets them to null if they are not possible for that cell. 我正在编写一个简单的数独求解器,它使用数字1-9组成的数组,如果该单元格不可能将它们设置为null。 An example is a cell where the answer can only be a 5, so all the numbers are set to null except for five. 一个示例是一个答案只能为5的单元格,因此除5外,所有数字均设置为null。 Then, I have a clean() function which deletes all the values from the array which are null, but that is not working correctly. 然后,我有一个clean()函数,该函数从数组中删除所有为null的值,但不能正常工作。 The original array is this. 原始数组是这个。

[null,null,null,null,5,null,null,null,null]

After being cleaned, it returns 清洗后返回

[null,null,5,null,null]

The javascript code is here, and the grid is the grid of numbers in the sudoku 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;
    }

Essentially, the array.splice is not splicing everything it needs to, and I don't know why 从本质上讲,array.splice不会拼接所需的所有内容,我也不知道为什么

You change the array while you iterate. 您在迭代时更改数组。 Try something like that: 尝试这样的事情:

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

The -- lower the index because the next item will then be at the same index than the item you are removing. --降低索引,因为下一个项目将与您要删除的项目处于相同的索引。

Moreover, objects and arrays passed as argument are passed by reference so you don't need to return anything. 而且,作为参数传递的对象和数组都是通过引用传递的,因此您无需返回任何内容。 You can do clean(possibs); 您可以clean(possibs);

That's because when you "splice" the array , the index change. 那是因为当您“拼接”数组时,索引会改变。 Maybe you can try this code : 也许您可以尝试以下代码:

function clean(array){
    var x = [];
    for(var i=0;i<array.length;i++){
        if(array[i]!=null){
            x.push(array[i]);
        }
    }
    return x;
}

try this: 尝试这个:

var array = [null,null,null,null,5,null,null,null,null];
for(var i=0;i<=array.length; ){
    if(array[i] === null){
        array.splice(i,1);
    } else if (array.length < 2) {
        break;
    } else {
        i++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM