JavaScript console prints assigned value of variable before it has been assigned?

后端 未结 8 780
Happy的楠姐
Happy的楠姐 2020-12-06 17:47

I\'m deeply confused by the behaviour of either JavaScript, or the Chrome console. Can someone help me understand?

Basically I have the following JavaScript code, no

相关标签:
8条回答
  • 2020-12-06 18:18

    that's because the copied_array is a reference, and console.log is executed asynchonously, so the content of the array is modifed before the first log prints it.

    you may copy the array before printing

    console.log([].concat(copied_array));
    
    0 讨论(0)
  • 2020-12-06 18:21

    It's the way arrays are displayed in the Chrome console, and that's by reference. If you want accurate results, convert to a string:

    var initial_array = [];
    
    function initialiseArray() { 
       initial_array = [2, 9, 8, 6, 0, 2, 1];
    } 
    
    function copyToNewArray() {
        var copied_array = [];
    
        console.log("COPIED 1", copied_array.toString());
    
        for (var i = 0; i < initial_array.length; i++) {
            var copy = initial_array[i];
            copied_array.push(copy);
        }
    
        console.log("COPIED 2", copied_array.toString());
    }
    
    initialiseArray();
    copyToNewArray();
    

    You can test this out pretty easily:

    var x = [];
    console.log(x), x.push(5), x; // outputs [5] and [5]
    
    0 讨论(0)
提交回复
热议问题