Reputation: 2094
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
Upvotes: 0
Views: 4079
Reputation: 5679
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.
Upvotes: 1
Reputation: 98
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.
Upvotes: 1