使用Object.create创建的Javascript数组-不是真正的数组

Javascript Arrays created with Object.create - not real Arrays?

本文关键字:数组 Javascript Object create 创建 使用      更新时间:2023-09-26

它看起来像是用Object.create创建的类似行走的数组和类似嘎嘎的数组,但仍然不是真正的数组。至少使用v8/node.js.

> a = []
[]
> b = Object.create(Array.prototype)
{}
> a.constructor
[Function: Array]
> b.constructor
[Function: Array]
> a.__proto__
[]
> b.__proto__
[]
> a instanceof Array
true
> b instanceof Array
true
> Object.prototype.toString.call(a)
'[object Array]'
> Object.prototype.toString.call(b)
'[object Object]'

一些Javascript大师能解释为什么会这样,以及如何使我新创建的数组与真正的数组无法区分吗?

我的目标是克隆数据结构,包括可能附加了自定义属性的数组。当然,我可以使用Object.defineProperty手动将属性附加到新创建的数组,但有没有使用Object.create的方法?

简短的答案是否定的。本文将对此进行详细解释。

不,不能。Object.create都是关于原型的,但[]Object.create(Array.prototype)都继承自同一个原型对象。

您称之为"所需Object.prototype.toString behavior"的是对象的内部[[Class]],这是用Object.create无法设置的。只有通过使用数组文字或调用Array构造函数才能创建"真正的数组"(具有Array类和特殊的数组行为索引属性.length)。