Arsen Petrov
Arsen Petrov

Reputation: 11

Why when I create an object with an array prototype I get an object

I created the variable p with a prototype array

const p = Object.create([])
console.log(p)

I have got the next result in Firefox Object { }, and chrome Array {}. When I use array methods they work as they should

p.push(1)
console.dir(p) //Object { 0: 1, length: 1 } OK

But when I use the assignment operator, I get the next result

p[1] = 2
console.dir(p) // Object { 0: 1, 1: 2, length: 1 } length !!!

Upvotes: 0

Views: 514

Answers (2)

York Chen
York Chen

Reputation: 754

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

So the result of Object.create([]) is an object. When you use "push" method for this object, actually it is found by following sequence:

  1. find the method under p object, not found.
  2. find the method under prototype reference of p, which is [], not found.
  3. find the method under prototype reference of [], which is Array.prototype.push

So when push is execute, the length is changed to 1. But if you assign value by yourself like

p[1] = 2

it is just a property under p object, length is not changed.

Upvotes: 2

laicuRoot
laicuRoot

Reputation: 31

You need to use the Array constructor to create an Array. Also bear in mind that Arrays are also objects.

Taking the example from mozilla:

let fruits = new Array('Apple', 'Banana');

console.log(fruits.length); // 2
console.log(fruits[0]);     // "Apple"

I would recommend you to read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array

Good luck in your learnings :)

Upvotes: 0

Related Questions