简体   繁体   English

如果原始类型被视为 object 那么它是否被视为数组?

[英]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'.当我们像本段下面的示例那样检索原始类型的描述符时,我们指定一个 integer 作为对象(它也成为属性的值),我们也指定键为“0”。 Now because we specified an integer as the key would this mean that from ES2015 onwards, the primitive type is considered an array?现在因为我们指定了 integer 作为键,这是否意味着从 ES2015 开始,原始类型被视为数组?

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

value of 'var e': '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 :当我们尝试获取原语的描述符时,它们首先根据规范转换为 object 形式:

20.1.2.8 Object.getOwnPropertyDescriptor ( O, P ) 20.1.2.8 Object.getOwnPropertyDescriptor (O, P)

When the getOwnPropertyDescriptor function is called, the following steps are taken:当调用getOwnPropertyDescriptor function时,采取以下步骤:

  1. Let obj be?让 obj 成为? ToObject(O).对象(O)。
  2. Let key be?让钥匙成为? ToPropertyKey(P). ToPropertyKey(P)。
  3. Let desc be?让 desc 成为? obj.[GetOwnProperty]. obj.[GetOwnProperty]。
  4. Return FromPropertyDescriptor(desc).返回 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.因此,我们从Object.getOwnPropertyDescriptor获得的任何信息都不会告诉我们有关原语本身的任何信息,它只会告诉我们有关从toObject步骤推出的 object 的属性的一些信息。

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

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