简体   繁体   中英

Concatenating Arrays in Constructor function

I'm having some trouble getting an array to concatenate. Not sure how best to exmplain this, but essentially I'd like that each iteration of a new node take the array from node.prevNodes and push the new array into the array with the previous content. Right now it IS doing that -sort of- but instead of a multidimensional array, it's just putting all the values in as a string into the array. See the below for more details..

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"]
    }
}

All the rest of the code is arbitrary to give some context to the basics of whats happening. I think it's either how newArr is created or how the prevNodes parameter is being sent. Stumped here...

So I've found a solution, though I don't think it's ideal. The problem was in both places I suspected and was solved with a few edits:

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

I'm honestly not sure why this worked (I understand in theory, just not in practice). If anyone else has a better way to do it, I'd love to know!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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