Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, arrays show different length in different places

I have no idea what is wrong with my array. I want to check is element in array with x and y equal to pos.x and pos.y. If it's not I want to push it. My code:

checkSteps(pos) {
    for(let i = 0; i < this.path.steps.length; i++){
        if(this.path.steps[i].x == pos.x && this.path.steps[i].y == pos.y) return false;
    }
    this.path.steps.push({
        x: pos.x,
        y: pos.y,
    });
    console.log(this.path);
    return true;
}

I don't know why I can't do this.path.steps.push(pos); instead of this.path.steps.push({x: pos.x,y: pos.y,});

This console.log() give me:

JSON

like image 540
czlowiek488 Avatar asked Feb 18 '26 04:02

czlowiek488


1 Answers

When you log an array or object (or anything that isn't a primitive), the console shows a line (snippet) of the object/array at the moment the log happens, and caches a reference to that object/array.

When you unfold the object/array later, the console uses that previously cached reference to list the object/array content. The object/array may have been changed by the time you unfold it, that's why the console give you this message:

console

To inform you that the values listed have just been (re)evaluated.

Demonstration:

Open your console and type this:

var arr = [];
console.log(arr);

setTimeout(function() {
    arr.push(0, 1, 2, 3, 4, 5);
    console.log("Unfold the above array now");
}, 5000);

Wait for the "Unfold the above array now" message and then unfold the previously logged empty array and see.

like image 70
ibrahim mahrir Avatar answered Feb 19 '26 17:02

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!