weird array behaviour in javascript

前端 未结 3 979
终归单人心
终归单人心 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.

提交回复
热议问题