Fra*_*rzi 0 javascript dictionary data-structures ecmascript-6 es6-map
假设有两个Map对象,如何检查它们的键集是否相同?
例如:
const A = new Map();
A.set('x', 123);
A.set('y', 345);
const B = new Map();
B.set('y', 567);
B.set('x', 789);
const C = new Map();
C.set('x', 121);
C.set('y', 232);
C.set('z', 434);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,两者A和B地图具有相同的密钥集(即['x', 'y']),而密钥集C是不同的,因为它具有额外的密钥z.
检查每个地图的size是相同的,然后遍历keys之一Map,检查重点在其他同样存在.利用Array.prototype.every.call意味着不需要创建中间数组:
const A = new Map();
A.set('x', 123);
A.set('y', 345);
const B = new Map();
B.set('y', 567);
B.set('x', 789);
const C = new Map();
C.set('x', 121);
C.set('y', 232);
C.set('z', 434);
const sameKeySet = (m1, m2) => (
m1.size === m2.size
&& Array.prototype.every.call(m1.keys(), key => m2.has(key))
);
console.log(sameKeySet(A, B));
console.log(sameKeySet(A, C));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |