Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]'

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?

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?

like image 601
Philippe Plantier Avatar asked Jan 26 '12 09:01

Philippe Plantier


People also ask

Can a JavaScript object be an array?

Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

Is array in JavaScript primitive or object?

Numbers, boolean values, and the null and undefined types are primitive. Objects, arrays, and functions are reference types. A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit.

How are arrays created in JavaScript?

Arrays can be created using a constructor with a single number parameter. An array with its length property set to that number and the array elements are empty slots.

Can you create an array with different data types in JavaScript?

JavaScript arrays can indeed contain any and all types of data. An array may contain other objects (including other arrays) as well as any number of primitive values like strings, null , and undefined .


2 Answers

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

like image 59
Tim Down Avatar answered Sep 19 '22 04:09

Tim Down


No, you cannot. Object.create is all about prototypes, but both [] and Object.create(Array.prototype) inherit from the same prototype object.

What you call "desired Object.prototype.toString behaviour" is the internal [[Class]] of the object, which is impossible to set up with Object.create. Creating "true arrays" (with an Array class and special array behaviour - indexed properties, .length) is only possible by using array literals or calling the Array constructor.

like image 42
Bergi Avatar answered Sep 19 '22 04:09

Bergi