有没有办法使用数字类型作为对象键? [英] Is there any way to use a numeric type as an object key?
问题描述
似乎当我在对象中使用数字类型作为键名时,它总是被转换为字符串。反正有没有把它作为数字存储?正常的类型转换似乎不起作用。
It seems that when I use a numeric type as a key name in an object, it always gets converted to a string. Is there anyway to actually get it to store as a numeric? The normal typecasting does not seem to work.
示例:
var userId = 1;
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);
Dir输出:
{
'1': 'a value'
}
我想要的是:
{
1: 'a value'
}
建议?
谢谢
推荐答案
不,这是不可能的。 密钥将始终转换为字符串。请参阅属性访问者文档
No, this is not possible. The key will always be converted to a string. See Property Accessor docs
属性名称必须是字符串。这意味着非字符串对象不能用作对象中的键。任何非字符串对象(包括数字)都通过toString方法转换为字符串。
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'
这篇关于有没有办法使用数字类型作为对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!