比较 ECMA6 集是否相等

2022-01-17 00:00:00 set javascript ecmascript-6

你如何比较两个 javascript 集?我尝试使用 ===== 但都返回 false.

How do you compare two javascript sets? I tried using == and === but both return false.

a = new Set([1,2,3]);
b = new Set([1,3,2]);
a == b; //=> false
a === b; //=> false

这两个集合是等价的,因为根据定义,集合没有顺序(至少通常不会).我查看了 在 MDN 上设置的文档 并没有发现任何有用的东西.有人知道怎么做吗?

These two sets are equivalent, because by definition, sets do not have order (at least not usually). I've looked at the documentation for Set on MDN and found nothing useful. Anyone know how to do this?

推荐答案

试试这个:

var a = new Set([1,2,3]);
var b = new Set([1,3,2]);

alert(eqSet(a, b)); // true

function eqSet(as, bs) {
    if (as.size !== bs.size) return false;
    for (var a of as) if (!bs.has(a)) return false;
    return true;
}

更实用的方法是:

var a = new Set([1,2,3]);
var b = new Set([1,3,2]);

alert(eqSet(a, b)); // true

function eqSet(as, bs) {
    return as.size === bs.size && all(isIn(bs), as);
}

function all(pred, as) {
    for (var a of as) if (!pred(a)) return false;
    return true;
}

function isIn(as) {
    return function (a) {
        return as.has(a);
    };
}

all 函数适用于所有可迭代对象(例如 SetMap).

The all function works for all iterable objects (e.g. Set and Map).

如果 Array.from 得到更广泛的支持,那么我们可以将 all 函数实现为:

If Array.from was more widely supported then we could have implemented the all function as:

function all(pred, as) {
    return Array.from(as).every(pred);
}

希望对您有所帮助.

相关文章