为何JS中带数字键的对象及数组无法使用点表示法访问?
Great question—this is a common point of confusion when learning how JavaScript handles objects and arrays. Let’s break this down step by step, using your examples as a guide.
First, let’s start with the core rule that governs property access in JavaScript: dot notation requires property names to be valid identifiers, while bracket notation accepts any string (or value that can be coerced to a string) as a property name.
Let’s walk through each of your code snippets:
console.log(arr[0]);
This works because when you pass a number inside square brackets, JavaScript automatically coerces it to a string (0→"0"). Arrays are just specialized objects where "indexes" are actually string property names matching integer values (from0to2^32 - 1). The engine optimizes these properties for array-like behavior (like auto-updating thelengthproperty), but at their core, they’re still regular object properties.console.log(arr['0']);
This is functionally identical to the first example—you’re directly using the string property name that the number0gets converted to. This confirms that array indexes are just string keys under the hood.console.log(arr.0);&console.log(arr.'0');
Both throw syntax errors for the same reason: dot notation doesn’t allow property names that aren’t valid identifiers. A valid JavaScript identifier can’t start with a number, and you can’t place a string literal directly after a dot. Even though"0"is a valid property name for the array object, the syntax rules of dot notation block you from using it this way.
What About the "Everything is an Object" Idea?
You’re totally right that arrays are objects in JavaScript—but that doesn’t mean all property access rules go out the window. Objects have two distinct ways to access properties:
- Dot notation: For valid identifiers (e.g.,
obj.username,obj._item123—note that underscores are allowed at the start) - Bracket notation: For any property name (including those that aren’t valid identifiers, like
"0","user preferences", or evenSymbol()keys)
When you try to simulate an array with a custom object (like const fakeArr = { 0: 'apple', 1: 'banana', length: 2 }), you’ll hit the exact same restriction: fakeArr.0 will throw an error, but fakeArr['0'] works perfectly. This aligns with how real arrays behave—they’re just objects with extra optimizations for integer-like string keys.
Quick Recap
- Array indexes are string property names in disguise, and JS coerces numbers to strings when using bracket notation.
- Dot notation is limited to valid identifiers, so numeric property names (like
"0") can’t be accessed this way. - The "everything is an object" principle holds true—arrays follow the same property access rules as regular objects, they just have special handling for index-like keys.
内容的提问来源于stack exchange,提问作者Ankit Kumar Ojha

