代码之家  ›  专栏  ›  技术社区  ›  Christian Vincenzo Traina

方法Set.prototype.调用了未定义的不兼容接收器

  •  3
  • Christian Vincenzo Traina  · 技术社区  · 6 年前

    我想计算两个 s、 所以我写道:

    let a = new Set([1, 2, 3]);
    let b = new Set([2, 3, 4]);
    
    let intersection = [...a].filter(x => b.has(x));
    
    console.log(intersection);

    它可以工作,但是我注意到我可以缩短上面的代码。因为filter方法只需要一个函数,不管它是如何定义的,都会调用它,我写道:

    let a = new Set([1, 2, 3]);
    let b = new Set([2, 3, 4]);
    
    let intersection = [...a].filter(b.has);
    
    console.log(intersection);

    Uncaught TypeError:方法Set.prototype.调用了未定义的不兼容接收器

    我也注意到如果我绑住 Set.prototype.add 到变量:

    let a = new Set([1, 2, 3]);
    let b = new Set([2, 3, 4]);
    
    let intersection = [...a].filter(Set.prototype.bind(b));
    
    console.log(intersection);

    b.has 不是有效的回调?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Sushanth --    6 年前

    has 方法失去内部 this 将其作为回调传递时的上下文。

    这就是当你使用 bind 提供正确的背景。

    有关更多信息,已记录在案 here

        2
  •  1
  •   robe007 Leo Aguirre    5 年前

    你可以使用 Array#filter 函数与传递 thisArg 作为第二个参数。所以 has this ,并继续进行评估或比较。

    function compare(a, b) {
        return [...a].filter(Set.prototype.has, b);
    }
    
    let a = new Set([1, 2, 3]);
    let b = new Set([2, 3, 4]);
    
    console.log(compare(a, b));

    另一个想法:

    function compare(a, b) {
        return new Set([...a].filter(Set.prototype.has, b));
    }
    
    let a = new Set([1, 2, 3]);
    let b = new Set([2, 3, 4]);
    
    console.log([...compare(a, b).values()]);