Javascript 时髦的数组事故 [英] Javascript Funky array mishap

查看:42
本文介绍了Javascript 时髦的数组事故的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function a() {
  var b = ["b"];
  console.log(b);
  //console.log(b.slice());
  b = b.push("bb"); 
}
a();

在一个完美"的世界里,你会认为 console.log 会显示 ["b"],但它显示的是 ["b", "bb"] 即使 "bb" 直到之后才被推送.

In a "perfect" world you would think that the console.log would show ["b"], but wildly enough it shows ["b", "bb"] even though "bb" isn't pushed on until afterwards.

如果你做console.log(b.slice()); 那么你会得到["b"] 想要的结果.这是为什么?这种并发症背后的原因是什么?我只是想更好地理解这一点,以便更好地避免它的发生.

If you do console.log(b.slice()); Then you will get the desired result of ["b"]. Why is that? What's the reason behind this complication? I just want to understand this better so I can better avoid it from happening.

* 注意我在我最近的一个问题中提到了同样的观点,但这是一个更简洁的例子.@RightSaidFred 带领我走到了这一步,到目前为止帮了我很大的忙.

* Note I hit on this same point in a recent question of mine, but this is a much more concise example. @RightSaidFred has led me to this point and has been a huge help so far.

JSFiddle 上的可运​​行示例

推荐答案

这是一个 已知问题 console.log.

不是在调用方法时将参数转换为字符串,而是将参数存储起来并在显示在 UI 中时转换为字符串.由于函数运行时 UI 中没有任何反应,因此您将看到退出函数时对象的状态.

Instead of turning the parameter into a string when you call the method, the parameter is stored and turned into a string when it's displayed in the UI. As nothing happens in the UI while the function is running, you will see the state of the object as it is when you exit the function.

这篇关于Javascript 时髦的数组事故的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆