1

我在连接数组时遇到了一些麻烦。不知道如何最好地解释这一点,但基本上我希望新节点的每次迭代都从中获取数组node.prevNodes并将新数组推送到具有先前内容的数组中。现在它正在做那种 - 排序 - 但不是多维数组,它只是将所有值作为字符串放入数组中。请参阅下面的详细信息。

function node(posX, posY, numMoves, prevNodes){
    this.posX = posX;
    this.posY = posY;
    this.numMoves = numMoves;
    this.prevNodes = [prevNodes];
}

nodes = []; // all nodes
nodes.push( new node(1, 1, 0) ); // add starting node

while (nodes.length != 0) {
    currentPos = nodes.shift();
    for (i = 0; i < 8; i++) { 

        newArr = currentPos.prevNodes + [x, y]; /* I think this is the issue */
        nodes.push( new node(x, y, d+1, newArr) );

        // Example Ideal value for newArr (after some iteration):
        // [[3,2],[5,3],[7,4],[6,2],[8,1]]

        // Actual value:
        // ["3,25,33,42,6"]
    }
}

所有其余的代码都是任意的,以便为发生的事情提供一些背景信息。我认为要么newArr是创建方式,要么是prevNodes参数的发送方式。被这里绊倒了……

4

1 回答 1

0

所以我找到了一个解决方案,虽然我不认为它是理想的。问题出在我怀疑的两个地方,并通过一些修改得到了解决:

function node(posX, posY, numMoves, prevNodes){
    this.posX = posX;
    this.posY = posY;
    this.numMoves = numMoves;
    this.prevNodes = prevNodes; // removed brackets here
}

nodes = []; // all nodes
nodes.push( new node(1, 1, 0, []) ); // added empty brackets to starting node parameter

while (nodes.length != 0) {
    currentPos = nodes.shift();
    for (i = 0; i < 8; i++) { 
        newArr = currentPos.prevNodes.concat([[x, y]]); // used concat & double wrapped in brackets
        nodes.push( new node(x, y, d+1, newArr) );
    }
}

老实说,我不确定为什么会这样(我在理论上理解,只是在实践中不理解)。如果其他人有更好的方法来做到这一点,我很想知道!

于 2018-10-05T05:23:18.040 回答