如何查看Javascript中es6代理的类型?
How to check the type of es6 proxy in Javascript?
我正在使用 ES6 代理。我已经创建了一个数组的代理,现在当我检查它给我的代理类型时,它是 Object
类型。
问题:
如何检查我创建的代理是用于数组还是对象?
示例:
const arr = ['a', 'b', 'c'];
const arrProxy = new Proxy(arr, {});
alert(typeof(arrProxy));
更新(解决方案):
我们应该使用 Array.isArray
而不是 typeof
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!');
}
正如其他答案所暗示的那样,您无法判断某物是否是代理。
所以你可能需要自己实现它。
示例来自:https://exploringjs.com/deep-js/ch_proxies.html#transparent-virtualization-and-handler-encapsulation
const proxies = new WeakSet();
export function createProxy(obj) {
const handler = {};
const proxy = new Proxy(obj, handler);
proxies.add(proxy);
return proxy;
}
export function isProxy(obj) {
return proxies.has(obj);
}
我正在使用 ES6 代理。我已经创建了一个数组的代理,现在当我检查它给我的代理类型时,它是 Object
类型。
问题:
如何检查我创建的代理是用于数组还是对象?
示例:
const arr = ['a', 'b', 'c'];
const arrProxy = new Proxy(arr, {});
alert(typeof(arrProxy));
更新(解决方案):
我们应该使用 Array.isArray
typeof
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!');
}
正如其他答案所暗示的那样,您无法判断某物是否是代理。
所以你可能需要自己实现它。
示例来自:https://exploringjs.com/deep-js/ch_proxies.html#transparent-virtualization-and-handler-encapsulation
const proxies = new WeakSet();
export function createProxy(obj) {
const handler = {};
const proxy = new Proxy(obj, handler);
proxies.add(proxy);
return proxy;
}
export function isProxy(obj) {
return proxies.has(obj);
}