This question already has an answer here:
I am facing a strange problem in Javascript. It may be due to lack of understanding from my side.
I have an array a1
:
var a1 = [1, 2, 3]
Then I add a new element to this array a1
a1['newEntry'] = 4
And then I create a new array a2
using a1
:
var a2 = Object.create(a1)
Then Array.isArray(a1)
returns true
, but Array.isArray(a2)
returns false
. What is happening here? Could you please explain how this is happening?
From the MDN documentation:
When you call
Object.create(a1)
you're not creating a real array, you are creating an object which looks like an array, but it's not. In fact, you could even try this:and see that the result is
true
for both the variables.Then what does
Array.isArray()
do? Well, it doesn't obviously use theisinstanceof
statement. To be sure the variable is a real array, it checks using theObject.prototype.toString()
method, like this:This is why calling
Array.isArray()
gives you these results: because it performs the above check. Now you are sure that, even ifa2
looks like an array, it is not an array at all.Also, to clarify: when you do
a1['newEntry'] = 4
you're not adding a new element to the array. You are instead creating the propertynewEntry
with value4
on your existing array. To add an element to an array, you should use thepush()
method, like this:Object.create() is creating an Object rather than an Array, thus when checking against Array.isArray(), it will return false.
Consider instead
Array.slice()
, e.g.var a2 = a1.slice(0);
Source: Clone Arrays with JavaScript