Array.prototype的返回值是对象还是数组?

Array.prototype
// [constructor: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, find: ƒ, …]

Array.prototype[0] // undefined

Array.prototype.concat // ƒ concat() { [native code] }

Array.prototype 输出的这个东西怎么看着像数组,但好像又不是数组,谁能解惑下?

thank you ~(#^.^#)

阅读 3.2k
4 个回答
> typeof Array.protype;
< 'object'

> Array.prototype instanceof Object;
< true

补充:

不知道哪位过路神仙踩的我,那我就要问问了,你要觉得我说的哪不对,你倒是给我评论说你有何高见呗?暗搓搓地就知道踩是几个意思?

我就一句话,一切以文档为准。

JS 的标准定义在编号为 ECMA-262 的文档里,咱们看现行版本 —— ECMAScript 2021。

有关 Array 的定义:

https://tc39.es/ecma262/#sec-...

Array objects are exotic objects that give special treatment to a certain class of property names.

翻译过来就是:“Array 是一个特殊对象,会对特定类型的属性名进行特殊处理。”

这里已经说明 Array 是个对象,但还没那么明显。

那么再看第 22.1.3 小节的描述:

https://tc39.es/ecma262/#sec-...

The Array prototype object has a [[Prototype]] internal slot whose value is %Object.prototype%.

翻译过来已经说明 Array 的 \[\[Prototype\]\] 就是 Object.prototype,原型指向是相同的,也就是 Array 和 Object 二者的类型相同。

最后看 MDN 上有关 Array.protype 的陈述:

https://developer.mozilla.org...

Note that the Array prototype object is itself an array.
鲜为人知的事实:Array.prototype 本身也是一个 Array

由此得出结论,JS 里 Array 类型是 Object,而 Array.prototypeArray,所以类型也是 Object

P.S. 最后再说一遍:Array 是 JS 的里高阶/内置对象(Built-in Class),它的类型(Type)是 Object。没有一个 Type 叫做 Array 的玩意儿。不要把其他语言里有关数组的概念往 JS 里套,JS 只提供了一个看着像数组的对象,并把它起名为 Array 了。

  • 首先肯定是 Array.prototype 返回值是数组
Array.isArray(Array.prototype)  // true


// 另外 

Array.isArray(Object.prototype) // false
此处应该得一分(嘿嘿)
  • 为什么 Array.prototype[0] // undefined, 因为 这个数组的的确确是个空数组,不信你看
Array.prototype.length // 0
  • 你看到的 Array.prototype里面 有 concat,这个更好解释了,因为 Array.prototype 本身也是一个对象,concat 是他的属性
typeof Array.prototype // object

另外这种情况 还包括函数,例如:

function fn () {}

fn.prop = {
    version: "v1.0.0"
}

fn.prop // {version: "v1.0.0"}~~~~

虽然是函数定义的存在,但是依然可以在作为对象特性的本身定义属性

js中有种存在叫类数组

先说结论:Array.prototype肯定是一个对象
理由:

1、类型检测为object
typeof Array.prototype // object
2、可以直接取自身存在的属性值
Boolean(Array.prototype.concat) // true
3、按照常识,对象的prototype属性肯定是个对象(至少不能是个数组)

至于:

Array.prototype[0] // undefined

很简单,一个普通对象(非类数组对象)的obj[0]也是undefined
至于:

Array.prototype
// [constructor: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, find: ƒ, …]

只是打印出来有点奇怪而已

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题