简体   繁体   中英

If an primitive type is considered an object then is it considered an array?

When we retrieve the descriptor of an primitive type like the example below this paragraph we specify an integer as the object(which becomes the value of the property as well) and we specify the key as well which is '0'. Now because we specified an integer as the key would this mean that from ES2015 onwards, the primitive type is considered an array?

var e = Object.getOwnPropertyDescriptor([50], 0);

value of 'var e':

{
       configurable: false,
       enumerable: true,
       value: 50,
       writable: false
}

Or in the next example we pass in a string value:

var e = Object.getOwnPropertyDescriptor("hello", 0);

Which yields somewhat different results:

configurable: false
enumerable: true
value: "h"
writable: false

Now if we pass in a string it is treated as an array as well. But it appears that only the first character is being preserved as the value. Why does this happen as well?

When we try to get the descriptor for primitives, they are first converted to an object form as per the spec :

20.1.2.8 Object.getOwnPropertyDescriptor ( O, P )

When the getOwnPropertyDescriptor function is called, the following steps are taken:

  1. Let obj be? ToObject(O).
  2. Let key be? ToPropertyKey(P).
  3. Let desc be? obj.[GetOwnProperty].
  4. Return FromPropertyDescriptor(desc).

and so any information we get from the Object.getOwnPropertyDescriptor will tell us nothing about the primitive itself, it only tells us something about the properties of the object that comes rolling out of the toObject step.

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