gpt4 book ai didi

javascript - 有没有办法使用数字类型作为对象键?

转载 作者:IT王子 更新时间:2023-10-29 02:50:56 25 4
gpt4 key购买 nike

似乎当我在对象中使用数字类型作为键名时,它总是被转换为字符串。无论如何实际上让它存储为数字?正常的类型转换似乎不起作用。

例子:

var userId = 1;
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);

目录输出:

{
'1': 'a value'
}

想要的是:

{
1: 'a value'
}

建议?

最佳答案

不,这是不可能的。 key 将始终转换为字符串。请参阅 Property Accessor docs

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

> var foo = {}
undefined

> foo[23213] = 'swag'
'swag'

> foo
{ '23213': 'swag' }

> typeof(Object.keys(foo)[0])
'string'

关于javascript - 有没有办法使用数字类型作为对象键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3633362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com