简体   繁体   English

无法将对象推送到数组

[英]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"}" “开始{distanceFromTop:1,distanceFromLeft:0,路径:Array(0),状态:“开始”}“

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 但是当我想将其添加到队列中时,我得到的结果看起来并不像一个空数组,但长度为0

"queue [{…}] length :0" “队列[{…}]长度:0”

Am i missing something obvious? 我缺少明显的东西吗? Tried to add it via queue[location] but it also didnt work 试图通过queue [location]添加它,但是也没有用

You should check up on the difference between let and var 您应该检查let和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. let只能在声明了它的作用域块中使用,在整个声明函数中var都位于var中,或者全局声明。 Changing the first three (the function and the two distance as well as the queue) variables to var should fix this for you. 将前三个变量(函数和两个距离以及队列)更改为var应该可以解决此问题。 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"} 队列{distanceFromTop:1,distanceFromLeft:1,路径:Array(0),状态:“开始”}

And if you change the console as, 如果您将控制台更改为

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

You can see the contents of the array too. 您也可以看到数组的内容。

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

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