Set 实例的 difference() 方法接受一个集合并返回一个新的集合,其中包含当前集合中存在但给定集合中不存在的所有元素。
语法
difference(other)
参数
other- : 一个 Set 对象,或者类集合对象。
返回值
一个新的 Set 对象,包含存在于当前集合但不存在于 other 中的所有元素。
描述
使用数学记号,差集的定义如下:
<math display="block"><semantics><mrow><mi>A</mi><mo>∖</mo><mi>B</mi><mo>=</mo><mo stretchy="false">{</mo><mi>x</mi><mo>∊</mo><mi>A</mi><mo>∣</mo><mi>x</mi><mo>∉</mo><mi>B</mi><mo stretchy="false">}</mo></mrow><annotation encoding="TeX">A\setminus B = {x\in A\mid x\notin B}</annotation></semantics></math>
使用维恩图表示:
两个圆重叠的维恩图。A 不与 B 重叠的区域是 A 和 B 的差集。
difference() 接受类集合对象作为 other 参数。方法要求 this 是一个 Set 实例,因为它直接检索存储在其中的底层数据,而不调用任何用户代码。然后,它的行为取决于 this 和 other 的大小:
- 如果
this的元素数量大于other.size,则通过调用keys()方法遍历other,并使用this中所有在other中未见过的元素构造一个新的集合。 - 否则,它会遍历
this中的元素,并使用this中的所有使other.has(e)返回假值的元素e构造一个新集合。
返回的集合的元素的顺序与 this 相同。
示例
使用 difference()
以下示例计算奇数集(<10)和完全平方集(<10)的差集。其结果是一组不是完全平方数的奇数。
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.difference(squares)); // Set(3) { 3, 5, 7 }
规范
浏览器兼容性
参见
core-js中Set.prototype.difference的 polyfill- Set.prototype.intersection()
- Set.prototype.isDisjointFrom()
- Set.prototype.isSubsetOf()
- Set.prototype.isSupersetOf()
- Set.prototype.symmetricDifference()
- Set.prototype.union()
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
