chrome 下一段代码的理解

来源:互联网 发布:大数据的前沿技术培训 编辑:程序博客网 时间:2024/06/13 18:26

记一次 代码理解

//Depending on the browser, the console shows a live link to the object. If you don't expand the object within the console until after the line that adds the .age property runs then when you do expand you'll see that property. Is that what you mean? One way to avoid this is to use console.log("obj1", JSON.stringify(obj)), to log a snapshot of the object at that moment. // chrome 开发环境下var obj = {name:"小明"};console.log("obj1",obj);// 1. {name:"小明",age:10}obj.age = 10;// 2. {"name":"小明",age:10}console.log("obj2",obj);

为什么 第一个 log 的结果不是 {name:"小明"}

产生这种结果的原因在于:
1. 浏览器对于 console.log 的行为表现是不一样的
2. 在firefox和 IE11 下的 输出结果和我们预料的一样
3. 在 chrome 下可以通过 JSON.stringify() 函数把 obj对象 “正常” 输出出来
4. 小结: 无论结果如何在 代码中对成员变量的使用都是一致的,符合我们日常的认识。

var obj = {name:"小明"};if ("age" in obj) {    console.log("obj1",obj);}obj.age = 10;console.log("obj2",obj);// {name:"小明",age:10}

所以说,这个现象还是浏览器的 特殊行为

原创粉丝点击