JavaScript中无值对象属性为何不显示?测试代码及疑问
Great question! Let's break down exactly what's happening in your code and why you're seeing that output.
Key Behavior to Understand: Reading vs. Assigning Properties
In JavaScript, merely reading an object property that doesn't exist does NOT automatically create that property on the object. The engine only adds a property to the object when you explicitly assign a value to it (even if that value is undefined).
Let's Walk Through Your Code Step by Step
Your code:
var x = new Object(); x.foo; console.log(x); console.log(x.length);
var x = new Object();
This creates an empty plain object:{}. No properties exist on it yet.x.foo;
Here you're attempting to read thefooproperty fromx. Sincefoodoesn't exist, JavaScript returnsundefined—but crucially, it doesn't addfooas a property tox. The object remains empty.console.log(x);
The console outputs{}becausexstill has no properties. The earlier read operation didn't modify the object at all.console.log(x.length);
Plain JavaScript objects don't have a built-inlengthproperty (that's for arrays, strings, and other array-like objects). So readingx.lengthalso returnsundefined, and again, nolengthproperty is added tox.
What Would Make the Property Appear?
If you want foo to show up in the object, you need to assign a value to it—even if that value is undefined:
var x = new Object(); x.foo = undefined; // Explicit assignment adds the property console.log(x); // Outputs: { foo: undefined }
Now foo is a property of x, so it appears in the console output, even though its value is undefined.
内容的提问来源于stack exchange,提问作者Robert

