简体   繁体   English

设置陷阱执行两次 - JS Proxy

[英]Set Trap execute for two times - JS Proxy

Im working with proxies in js, but something is weird =>我在 js 中使用代理,但有些东西很奇怪 =>

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.count(); //this execute for two times!
    if(typeof val === 'string') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');

The Set trap should call only once when i push to the array, but it executed twice.当我推送到数组时, Set陷阱应该只调用一次,但它执行了两次。

And there is an error in the console, when i push to array =>当我推送到数组时,控制台出现错误 =>

Uncaught TypeError: proxy set handler returned false for property '"length"'

How can i fix this and what's wrong?我该如何解决这个问题?出了什么问题?

Calling Array#push causes set to be called two times:调用Array#push会导致set被调用两次:

  1. target=[], prop=0, val=Manuel : Adds a new value to an index target=[], prop=0, val=Manuel :向索引添加新值
  2. target=["Manuel"], prop=length, val=1 : Updates length of array target=["Manuel"], prop=length, val=1 : 更新数组的长度

In your case, the second call is returning false since the length value is numeric.在您的情况下,第二次调用返回 false,因为长度值是数字。

A possible solution:一个可能的解决方案:

 let _usernames = []; _usernames = new Proxy(_usernames, { set(target, prop, val) { console.log(target, prop, val); if(typeof val === 'string' || prop === 'length') { target[prop] = val; return true; } else { return false; } } }); _usernames.push('Manuel');

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

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