Array.isArray() returns false for array created wi

2019-08-10 23:16发布

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?

2条回答
相关推荐>>
2楼-- · 2019-08-11 00:05

From the MDN documentation:

The Object.create() method creates a new object with the specified prototype object and properties.

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:

> a1 instanceof Array
true
> a2 instanceof Array
true

and see that the result is true for both the variables.

Then what does Array.isArray() do? Well, it doesn't obviously use the isinstanceof statement. To be sure the variable is a real array, it checks using the Object.prototype.toString() method, like this:

> Object.prototype.toString.call(a1)
"[object Array]"
> Object.prototype.toString.call(a2)
"[object Object]"
> Object.prototype.toString.call(a1) === "[object Array]"
true
> Object.prototype.toString.call(a2) === "[object Array]"
false

This is why calling Array.isArray() gives you these results: because it performs the above check. Now you are sure that, even if a2 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 property newEntry with value 4 on your existing array. To add an element to an array, you should use the push() method, like this:

> a1 = [1, 2, 3]
> a1.push(4)
> console.log(a1)
[1, 2, 3, 4]
查看更多
神经病院院长
3楼-- · 2019-08-11 00:23

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

查看更多
登录 后发表回答