简体   繁体   English

Javascript:在代理中陷阱“ in”运算符

[英]Javascript: Trap “in” operator in proxy

I have a proxy something like this: 我有这样的代理:

var pr = new Proxy([],...);

Without giving all the gory details, it is set up to trap integers and return objects from another (actual) array "B" at the corresponding index. 在不提供所有详细信息的情况下,将其设置为捕获整数并从相应索引处的另一个(实际)数组“ B”返回对象。 So, eg, pr[3] would return B[3].someProperty. 因此,例如pr [3]将返回B [3] .someProperty。 It also traps "length" and returns the length of array "B". 它还捕获“长度”并返回数组“ B”的长度。 However, values are never actually assigned directly to the pr "array". 但是,实际上从未将值直接直接分配给pr“数组”。 So you see it is sort of a "pseudo" array. 因此,您看到它有点像“伪”数组。 It is merely reflecting array "B", and contains no actual values. 它仅反映数组“ B”,不包含任何实际值。

The problem comes in when the test (someinteger in pr) is run. 问题在运行测试(pr中的someinteger)时出现。 Of course from what I described, this test would always return false. 当然,根据我的描述,该测试将始终返回false。 This test does not seem to run code in the proxy so I can't seem to trap it and compute a return for it. 该测试似乎未在代理中运行代码,因此我似乎无法捕获它并为其计算收益。 Or can I? 可以吗

This creates a problem with Array.prototype iterator methods because many of them perform that test. 这会导致Array.prototype迭代器方法出现问题,因为其中许多方法会执行该测试。 I could write my own corresponding methods as traps in the proxy, but I would like to find a simpler way. 我可以将自己的相应方法编写为代理中的陷阱,但我想找到一种更简单的方法。 If there was a way to handle the "in" operator, that would save a lot of extra code. 如果有一种方法可以处理“ in”运算符,则可以节省很多额外的代码。

Is there something that I am not seeing, or a way to work around this? 是否有我看不见的东西,或者解决此问题的方法?

proxy has a trap for in , it is called has : 代理有一个陷阱in ,它被称为has
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/has https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/has

var a = "abcd".split("");
var pr = new Proxy(a, {
    has: function(target, prop) {
        return (prop === "length" || +prop === (prop >>> 0) && +prop < target.length);
    },

    get: function(target, prop) {
        if(prop === "length") return target.length;

        if(+prop === (prop >>> 0) && +prop < target.length)
            return target[prop];
        return void 0;
    }
});

console.log(2 in pr, pr[2]);
console.log(5 in pr, pr[5]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM