简体   繁体   中英

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.

Any reason, why its string and not a number ?

Keys are always of a String type. 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() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. 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.

As per the documentation Object.keys() returns string array

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. 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()

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

Javascript Object has no number keys! All keys are Strings. Always.

If you want to map other things to values you should use a Map .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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