JavaScript对象中obj.key形式删除操作是否仅支持字符串键?非字符串键删除方式解析
Great question! Let's unpack what's happening here and answer your core questions clearly.
First, a quick foundational note: All object keys (except Symbols) are implicitly converted to strings in JavaScript. So when you define const a = {a: 1, 0: 2}, the key 0 is actually stored as the string "0" under the hood.
Why delete a.0 throws an error
The dot notation (obj.key) has strict syntax rules: the part after the dot must be a valid JavaScript identifier. Valid identifiers can't start with a number, can't contain hyphens/spaces, and can't be reserved keywords. Since 0 starts with a number, it's not a valid identifier—so a.0 is a syntax error before the delete operation even runs.
Answering your questions
Does
obj.key-style deletion only work for string-type keys?
More precisely: it only works for keys that are valid JavaScript identifiers (which are treated as strings). Not all string keys qualify—for example, keys like"0","user-name", or"123abc"can't be accessed with dot notation, even though they're strings. You'll need square brackets for those cases.Do non-string keys require
obj[key]syntax for deletion?
Let's break this down by key type:- Number keys: As we saw, numbers are converted to strings, but you can't use dot notation (since numbers aren't valid identifiers). You must use
obj[key](eitherobj[0]orobj["0"]—both work, since0gets coerced to"0"). - Symbol keys: Symbols are a special key type that aren't converted to strings. Dot notation doesn't support Symbols, so you have to use
obj[mySymbol]to delete them. - Other non-string types: Any other non-string (like a boolean or object) will be converted to a string when used as a key, but again, if the resulting string isn't a valid identifier, you'll need square brackets.
- Number keys: As we saw, numbers are converted to strings, but you can't use dot notation (since numbers aren't valid identifiers). You must use
Example to confirm
For your original object:
const a = {a: 1, 0: 2}; delete a.a; // Works, since "a" is a valid identifier delete a["0"]; // Works, accesses the string key "0" delete a[0]; // Also works, since 0 is coerced to "0" delete a.0; // Syntax error—invalid identifier
内容的提问来源于stack exchange,提问作者David542

