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

why does the browser console display the result at the first? I think the reuslt should be an unchanged object {name:"小明"}.Now ,I have a headache about it . appreciate your response.

  • 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. – nnnnnn Sep 28 '17 at 03:17

3 Answers3

1

This is because you are seeing/expanding the object after adding the new property age. Initially the object has only one property but by the time you are inspecting it , a new key will be added to the object

enter image description here

Another way is to verify using hasOwnProperty. In below snippet the first console.log statement won't be executed since the object does not have the key age

var obj = {
  name: "小明"
};
if (obj.hasOwnProperty('age')) {
  console.log("obj1", obj);
}
obj.age = 10;
console.log("obj2", obj);
brk
  • 48,835
  • 10
  • 56
  • 78
0

When you expand the object the values displayed in the console are evaluated at runtime.

Tooltip in Chrome console explaining that values are evaluated at runtime:

Tooltip in Chrome console explaining that values are evaluated at runtime

You could try JSON.stringify to print the current value to the console.

e.g.

console.log("obj1", JSON.stringify(obj));
H77
  • 5,859
  • 2
  • 26
  • 39
0

This depends on the browser. If I recall correctly, chrome logs an unchanging object whereas firefox logs a changing one. Either way, obj.age will be undefined until you define it.

EKW
  • 2,059
  • 14
  • 24