使用复杂的对象/数组作为关键是否“按预期”工作?

发布于 2025-01-04 06:35:55 字数 298 浏览 1 评论 0原文

我需要一组“复杂的事物”,其中“复杂的事物”是数字或字符串的数组。

我可以为此使用普通对象吗?

示例:

var set = {};
set[[1,2]] = 1;
set[[1,2]] = 1;
set[["string", "another string"]] = 1;
set[["string", "another string"]] = 1;

现在我期望 set 中有两个键/值对,并且在 Chrome 中进行测试证实确实如此。依赖这种行为安全吗?

I need a set of "complex things", where a "complex thing" is an array of numbers or strings.

Can I use a plain object for this?

Example:

var set = {};
set[[1,2]] = 1;
set[[1,2]] = 1;
set[["string", "another string"]] = 1;
set[["string", "another string"]] = 1;

Now I expect that there are two key/value pairs in set, and testing in Chrome confirms that it is the case. Is it safe to rely on this behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾挽 2025-01-11 06:35:55

一点也不。

对象键只能是字符串或数字。
复杂对象将通过调用toString()转换为字符串。

您可以在规范中看到这一点:

令 propertyNameString 为 ToString(propertyNameValue)。

因此,set[ [1,2] ]set["1,2"] 相同。

Not at all.

Object keys can only be strings or numbers.
Complex objects will be converted to strings by calling toString().

You can see this in the spec:

Let propertyNameString be ToString(propertyNameValue).

Therefore, set[ [1,2] ] is the same as set["1,2"].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文