You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript对象中obj.key形式删除操作是否仅支持字符串键?非字符串键删除方式解析

Understanding Property Deletion Syntax in JavaScript

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

  1. 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.

  2. 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] (either obj[0] or obj["0"]—both work, since 0 gets 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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:17:40