Array.isArray()对于使用Object.create()创建的数组返回false [英] Array.isArray() returns false for array created with Object.create()
问题描述
我在JavaScript中遇到了一个奇怪的问题.这可能是由于我缺乏了解.
I am facing a strange problem in Javascript. It may be due to lack of understanding from my side.
我有一个数组a1
:
var a1 = [1, 2, 3]
然后我向该数组a1
a1['newEntry'] = 4
然后使用a1
创建一个新数组a2
:
And then I create a new array a2
using a1
:
var a2 = Object.create(a1)
然后Array.isArray(a1)
返回true
,但是Array.isArray(a2)
返回false
. 这是怎么回事?您能解释一下这是怎么回事吗?
Then Array.isArray(a1)
returns true
, but Array.isArray(a2)
returns false
. What is happening here? Could you please explain how this is happening?
推荐答案
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
这就是为什么调用Array.isArray()
会为您提供这些结果的原因:因为它执行上述检查.现在,您可以确定即使a2
看起来像一个数组,它也不是一个数组.
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.
另外,要澄清一下:当您执行a1['newEntry'] = 4
时,您没有在数组中添加新元素.您将在现有数组上创建值为4
的属性newEntry
.要将元素添加到数组,应使用push()
方法,如下所示:
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]
这篇关于Array.isArray()对于使用Object.create()创建的数组返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!