简体   繁体   English

object 中 javascript 数组的奇怪行为

[英]strange behaviour on javascript array in an object

i am getting a strange javascript array behaviour when im pushing a value inside an array which resides in an object.当我将一个值推入驻留在 object 中的数组中时,我得到了一个奇怪的 javascript 数组行为。 the array in initially empty and then i push a value into it.数组最初是空的,然后我将一个值推入其中。 now the strange behaviour is that, i console log the obj before and after pushing the value.现在奇怪的行为是,我在推送值之前和之后控制台记录 obj。 in the console.log before pushing, the array inside the object should be empty but its giving the array after operation in console log.在推送之前的console.log中,object中的数组应该是空的,但是它在控制台日志中给出了操作后的数组。

let myObj = [{key1: 'hello', key2: []}];

console.log(myObj);

myObj[0].key2.push(1);

console.log(myObj); 

both the console logs in the above code give [ { "key1": "hello", "key2": [ 1 ] } ]上面代码中的控制台日志都给出 [ { "key1": "hello", "key2": [ 1 ] } ]

How is this possible这怎么可能

If your console is a browser, oftentimes the code will execute at a different time than when the logging occurs.如果您的控制台是浏览器,则代码的执行时间通常与日志记录发生的时间不同。 In Chrome, where I took this screenshot, a little "i" icon appears that indicates that the value was computed at a later time.在我截取此屏幕截图的 Chrome 中,会出现一个小“i”图标,表示该值是稍后计算的。

What is likely happening is that the console is displaying the content after it was already updated.可能发生的情况是控制台在内容已更新显示内容。

控制台在更改前后记录相同的值

From what I understand, this is a performance-optimizing feature that allows for the console to store a reference to the object being logged, and will only load its value once the console.log function (ie, the browser) is asked to do so.据我了解,这是一项性能优化功能,允许控制台存储对正在记录的 object 的引用,并且只会在 console.log function(即浏览器)被要求这样做时加载其值.

Edit: And to demonstrate this further, using a Node console environment to run your code does in fact produce the results you expected, since it evaluates the object's value during the log synchronously.编辑:为了进一步证明这一点,使用 Node 控制台环境运行代码实际上会产生您预期的结果,因为它会在日志期间同步评估对象的值。 Ignore the undefined s here:忽略这里的undefined

> let myObj = [{key1: 'hello', key2: []}];

> console.log(myObj);
[ { key1: 'hello', key2: [] } ]

> myObj[0].key2.push(1);

> console.log(myObj); 
[ { key1: 'hello', key2: [ 1 ] } ]

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

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