我正在使用ES6代理。我已经创建了一个数组的代理,现在当我检查它给我的代理类型为Object
类型。
题:
如何检查我创建的代理是用于数组还是对象?
例:
const arr = ['a', 'b', 'c'];
const arrProxy = new Proxy(arr, {});
alert(typeof(arrProxy));
更新(解决方案):我们应该使用typeof
而不是使用Array.isArray
const arr = ['a', 'b', 'c'];
const arrProxy = new Proxy(arr, {});
alert(Array.isArray(arrProxy));
你不能说代理是一个代理。这是他们的一部分,他们提供围绕另一个对象的立面(一个你无法检测到的)。
至于看你的arrProxy
的代码可以告诉它,它是一个数组:
const arr = ['a', 'b', 'c'];
const arrProxy = new Proxy(arr, {});
console.log(Array.isArray(arrProxy)); // true
另外:typeof
非常通用,它为你提供了大量的东西"object"
:任何物体(非原始)类型(包括null
)。所以typeof new Map()
,typeof new Set()
,typeof null
,typeof document
(在浏览器上)等都会给你"object"
。 (另请注意,typeof
是一个运算符,而不是函数;在代码示例中不需要()
。)
使用instanceof还有一种方法可以做到这一点:
if (arrProxy instanceof Array) {
console.log('This is an array!');
}