用相同的关键名称声明对象

发布于 2025-02-08 09:37:39 字数 111 浏览 2 评论 0原文

有没有办法在JS中声明具有相同密钥名称的对象?

let Obj = {
   '1' : '1',
   '1' : '1',
   '1' : '1',
}

Is there a way to declare a Object with the same key names in js ?

let Obj = {
   '1' : '1',
   '1' : '1',
   '1' : '1',
}

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

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

发布评论

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

评论(1

铃予 2025-02-15 09:37:39

否。对象中属性的名称必须是唯一的,尤其是您可以识别要获得/设置的属性。尽管您编写的代码将解析和运行,但结果对象将仅具有一个属性(最后一个使用该名称):

let obj = {
    1: "first",
    1: "second",
    1: "third",
};
console.log(obj[1]);; // "third"

如果关键名称必须相同,则可以使用一系列对象:

let array = [
    {1: 1},
    {1: 1},
    {1: 1},
];

...或者,实际上,只是一个数组(let array = [1,1,1];)作为密钥名称如果总是相同的话,没有做任何有用的事情。

No. The names of the properties in an object must be unique, not least so you can identify the property you want to get/set. Although the code you wrote will parse and run, the resulting object will have only one property (the last one using that name):

let obj = {
    1: "first",
    1: "second",
    1: "third",
};
console.log(obj[1]);; // "third"

You could use an array of objects if the key name must be the same:

let array = [
    {1: 1},
    {1: 1},
    {1: 1},
];

...or, really, just an array (let array = [1, 1, 1];) as the key name isn't doing anything useful if it's always the same.

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