比较 ECMA6 集是否相等 [英] comparing ECMA6 sets for equality

查看:22
本文介绍了比较 ECMA6 集是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何比较两个 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);
}

希望对您有所帮助.

这篇关于比较 ECMA6 集是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆