weird array behaviour in javascript

前端 未结 3 927
终归单人心
终归单人心 2020-12-21 17:00

I know arrays in javascript are a bit special, compared to other languages, but I don\'t really get this behaviour, or what\'s going on here.

I\'d like to know why i

相关标签:
3条回答
  • 2020-12-21 17:28

    The issue is when you call console.log(arr) it puts a reference to the array in the console that gets dereferenced when you "open" it (click on the arrow) so it will display changes that are made later in code. Use console.table(arr) or console.log(JSON.stringify(arr)) instead.

    Here is a snippet from MDN

    Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open.

    0 讨论(0)
  • 2020-12-21 17:32

    This behaviour isn't limited to arrays, any object behaves this way in the console

    What you are seeing is the result of console in all browsers "lying" to you

    if you console.log(anyobject) and inspect that object in the console, what you will see is current anyobject - not what it was when console.log was executed

    var obj = {}
    console.log(obj);
    obj.test = 1;
    
    var arr = [1];
    console.log(arr);
    arr.push(2);

    Now, if you open the developer console, click on the Object, you'll see test:1

    Look at the array in the console - it is output as [1] ... yet, click on the array you see both elements

    Note: chrome developer console does at least hint at the fact that it's lying to you - there's a blue i, if you hover (or click, can't recall, don't use Chrome often enough) you'll see a message saying that the value shown is evaluated just now

    0 讨论(0)
  • 2020-12-21 17:55

    arr is a parameter to your function already, and it is not undefined. var gets hoisted, so to the interpreter, your current code actually looks something like:

    function setupWindowProgBar(settings, window, palette, arr){
      var arr; // **does not reassign the parameter**
      console.log('start');
      console.log(arr);
      if(typeof arr == 'undefined'){
        arr = [];
      }
      console.log(arr);
      console.log('stop');
    }
    

    You should never be declaring a variable whose name is already scoped to the block/function you're using it in.

    If arr actually isn't defined in the argument, then it will be assigned to an array on the line arr = [];, but at least on Chrome, that empty array will not necessarily be printed at the time you console.log it.

    console.log(arr); does not necessarily immediately display the arr - depending on your browser, it may only be populated in your console after you open your console, after this line has run:

    arr[arr.length] = createProgBar('master', 'bg', window, ...
    
    0 讨论(0)
提交回复
热议问题