比较ECMA6套平等 [英] comparing ECMA6 sets for equality

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

问题描述

如何比较两个JavaScript集?我尝试使用 == === ,但都返回false。

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

这两套是等效的,因为根据定义,集没有订单(至少不是通常)。我查看了在MDN上设置的文档并没有发现任何有用的。任何人都知道如何做?

解决方案

尝试这样:



  var a = new Set([1,2,3]); var b = new Set([1,3,2]); alert(eqSet(a,b)); // truefunction eqSet(as,bs){if(as.size!== bs.size)return false; for(var a of as)if(!bs.has(a))return false;返回true;}  



一个更有效的方法是: p>

 



code>函数适用于所有可迭代对象(例如 Set Map )。



如果 Array.from 被更广泛的支持,那么我们可以实现全部功能如下:

  function all(pred,as){
return Array.from (如)。每(预解码值);
}

希望有所帮助。


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

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?

解决方案

Try 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;
}

A more functional approach would be:

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);
    };
}

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

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);
}

Hope that helps.

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

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