使用Object.create创建的Javascript数组 - 不是真正的数组? [英] Javascript Arrays created with Object.create - not real Arrays?

查看:127
本文介绍了使用Object.create创建的Javascript数组 - 不是真正的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来像使用Object.create创建的数组像Arrays一样走路,像Qurays一样嘎嘎,但仍然不是真正的数组。至少使用v8 / node.js。

It looks like Arrays created with Object.create walk like Arrays and quack like Arrays, but are still not real arrays. At least with 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专家解释了为什么会这样,以及如何使我的新创建的数组与真正的数组无法区分?

Can some Javascript guru explain why it is so, and how to make it so that my newly created array is indistinguishable from a real array?

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

My goal here is to clone data structures, including Arrays which may have custom properties attached. I could, of course, manually attach properties to a newly-created Array using Object.defineProperty, but is there a way to do so using Object.create?

推荐答案

简短的回答是否定的。 这篇文章解释了它所有细节。

The short answer is no. This article explains it all in some detail.

这篇关于使用Object.create创建的Javascript数组 - 不是真正的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆