Javascript 有没有办法使用数字类型作为对象键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3633362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to use a numeric type as an object key?
提问by Spot
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.
似乎当我在对象中使用数字类型作为键名时,它总是被转换为字符串。反正有没有真正让它存储为数字?正常的类型转换似乎不起作用。
Example:
例子:
var userId = 1;
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);
Dir Output:
目录输出:
{
'1': 'a value'
}
What I wantis this:
我想要的是这个:
{
1: 'a value'
}
Advice?
建议?
回答by Matthew Flaschen
No, this is not possible. The key will always be converted to a string.See 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.
属性名称必须是字符串。这意味着非字符串对象不能用作对象中的键。任何非字符串对象,包括数字,都通过 toString 方法类型转换为字符串。
> var foo = {}
undefined
> foo[23213] = 'swag'
'swag'
> foo
{ '23213': 'swag' }
> typeof(Object.keys(foo)[0])
'string'
回答by corvid
In an object, no, but I have found Mapextremely useful for this application. Here is where I have used it for numeric keys, a key-based event.
在一个对象中,不,但我发现Map对这个应用程序非常有用。这是我将它用于数字键的地方,这是一个基于键的事件。
onKeydown(e) {
const { toggleSidebar, next, previous } = this.props;
const keyMapping = new Map([
[ 83, toggleSidebar ], // user presses the s button
[ 37, next ], // user presses the right arrow
[ 39, previous ] // user presses the left arrow
]);
if (keyMapping.has(e.which)) {
e.preventDefault();
keyMapping.get(e.which)();
}
}
回答by Rob Olmos
Appears to be by design in ECMA-262-5:
在 ECMA-262-5 中似乎是设计使然:
The Property Identifier type is used to associate a property name with a Property Descriptor. Values of the Property Identifier type are pairs of the form (name, descriptor), where name is a String and descriptor is a Property Descriptor value.
属性标识符类型用于将属性名称与属性描述符相关联。属性标识符类型的值是形式(名称,描述符)的对,其中名称是一个字符串,描述符是一个属性描述符值。
However, I don't see a definite specification for it in ECMA-262-3. Regardless, I wouldn't attempt to use non-strings as property names.
但是,我在 ECMA-262-3 中没有看到明确的规范。无论如何,我不会尝试使用非字符串作为属性名称。
回答by Chittrang Mishra
Do we need something like this?
我们需要这样的东西吗?
var userId = 1;var myObject ={};
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);
Console: Object
控制台:对象
1 : "a value"
1:“一个值”
回答by Shivam Sharma
I think you can do the following if you want to use the above thing for accessing it like as a number, I did the same and worked.
我认为如果你想使用上面的东西像数字一样访问它,你可以做以下事情,我做了同样的工作。
var myObj = {"0":"a","1":"b","CNT":2};
$.each(myObj,function(key,value){
if(isNaN(parseInt(key))){
return true; //continue;
}
//Code to perform operation
}
This works only when the key doesn't start with and numeric character otherwise it'll be converted to a number. See the following example:
这仅在键不以数字字符开头时才有效,否则它将被转换为数字。请参阅以下示例:
parseInt("45kjghk") === 45
I used jQuery here
我在这里使用了 jQuery
Updated:
更新:
var myObj = {"0":"a","1":"b","CNT":2};
$.each(myObj,function(key,value){
if(isNaN(parseInt(key)) || (key.length !== parseInt(key).toString().length) ){
return true; //continue;
}
//Code to perform operation
}
It may overcome the above problem. Please suggest better if available and problem with this answer if there are.
它可以克服上述问题。如果有的话,请提出更好的建议,如果有的话,请提出这个答案的问题。
回答by William Niu
In JavaScript, numerical strings and numbers are interchangeable, so
在 JavaScript 中,数字字符串和数字是可以互换的,所以
myObject[1] == myObject['1']
If you really want number to be the key for an object, you might want an array (i.e. created with new Array()or []).
如果您真的希望 number 作为对象的键,您可能需要一个数组(即使用new Array()或创建[])。

