问题
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?
回答1:
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]
回答2:
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
来源:https://stackoverflow.com/questions/34178006/array-isarray-returns-false-for-array-created-with-object-create