简体   繁体   English

为什么Object.keys返回字符串数组而不是Numbers数组

[英]Why Object.keys is returns array of string instead of array of Numbers

When I run following code 当我运行以下代码时

var obj = { 0: 'a', 1: 'b', 2: 'c' };
typeof Object.keys(obj)[0] //returns string

In obj object i'm creating Number keys. obj对象中我正在创建数字键。

Any reason, why its string and not a number ? 任何原因,为什么它的字符串而不是number

Keys are always of a String type. 始终为String类型。 If you need numbers you will have to cast them manually: 如果您需要数字,则必须手动投射:

 var obj = { 0: 'a', 1: 'b', 2: 'c' }; var ids = Object.keys(obj).map(Number); console.log(ids); 

Because Object.keys returns an array with strings 因为Object.keys返回一个包含字符串的数组

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. Object.keys()返回一个数组,其元素是与直接在对象上找到的可枚举属性相对应的字符串。 The ordering of the properties is the same as that given by looping over the properties of the object manually. 属性的顺序与手动循环对象的属性所给出的顺序相同。

You get an array of strings, because Property names are strings by definition. 你得到一个字符串数组,因为属性名称是字符串的定义。

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方法进行类型转换为字符串。

As per the documentation Object.keys() returns string array 根据文档, Object.keys()返回字符串数组

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. Object.keys()返回一个数组,其元素是与直接在对象上找到的可枚举属性相对应的字符串 The ordering of the properties is the same as that given by looping over the properties of the object manually.( Taken from here ) 属性的顺序与通过手动循环对象的属性给出的顺序相同。( 取自此处

If you want to convert it to number array then use map() 如果要将其转换为数字数组,请使用map()

 var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(typeof Object.keys(obj).map(Number)[0]) 

Javascript Object has no number keys! Javascript对象没有数字键! All keys are Strings. 所有键都是字符串。 Always. 总是。

If you want to map other things to values you should use a Map . 如果要将其他内容映射到值,则应使用Map

 var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(typeof Object.keys(obj).map(Number)[0]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM