简体   繁体   中英

Can't push object to array

I have this simple code

let pathFinder = (entranceX, entranceY, grid) => {
            let distanceFromTop = entranceX;
            let distanceFromLeft = entranceY;

            let location = {
                distanceFromTop: distanceFromTop,
                distanceFromLeft: distanceFromLeft,
                path: [],
                status: 'Start'
            }


            console.log('start', location)

            let queue = [];
            queue.push(location);
            console.log('queue', queue)
}

And I made sure that "location" is not empty, it shows just fine in the console as:

"start {distanceFromTop: 1, distanceFromLeft: 0, path: Array(0), status: "Start"}"

but when I want to add it to the queue I end up with something that doesnt look like an empty array, but the length is 0

"queue [{…}] length :0"

Am i missing something obvious? Tried to add it via queue[location] but it also didnt work

You should check up on the difference between let and var

var pathFinder = (entranceX, entranceY, grid) => {
        var distanceFromTop = entranceX;
        var distanceFromLeft = entranceY;

        let location = {
            distanceFromTop: distanceFromTop,
            distanceFromLeft: distanceFromLeft,
            path: [],
            status: 'Start'
        }


        console.log('start', location)

        var queue = [];
        queue.push(location);
        console.log('queue', queue)
}

Let can only be used in the scope block in which it's declared where as var is throughout the function it is declared or globally. Changing the first three (the function and the two distance as well as the queue) variables to var should fix this for you. If not changing them all definitely would.

Looks like the push is working but the array is not being displayed while logging the whole object

queue.push(location);
console.log("queue", queue[0]);

queue {distanceFromTop: 1, distanceFromLeft: 1, path: Array(0), status: "Start"}

And if you change the console as,

console.log("queue", Array.from(queue));

You can see the contents of the array too.

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