Array.isArray()对于使用Object.create()创建的数组返回false [英] Array.isArray() returns false for array created with Object.create()

查看:64
本文介绍了Array.isArray()对于使用Object.create()创建的数组返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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?

推荐答案

来自

Object.create()方法使用指定的原型对象和属性创建新对象.

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

调用Object.create(a1) 时,您不是在创建 real 数组,而是在创建一个看起来像数组的对象,但事实并非如此.实际上,您甚至可以尝试以下方法:

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

并看到两个变量的结果均为true.

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

那么Array.isArray()的作用是什么?好吧,它显然没有使用isinstanceof语句.为确保变量是 real 数组,它使用Object.prototype.toString()方法,就像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆