<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>使用Set执行并集</title>
<script src="../unitl/test.js"></script>
<style>
#results li.pass {color:green;}
#results li.fail {color:red;}
</style>
</head>
<body>
<div id="firstElement"></div>
<div id="secondElement"></div>
<ul id="results"></ul>
</body>
<script>
//Set 不能存在相同的元素,Set成员的值都是唯一的。
const ninjas = ["Kuma","Hattori","Yagyu"];
const samurai = ["Hattori","Oda","Tomoe"];
//创建两个数组的并集。
const warriors = new Set([...ninjas,...samurai]);
//验证新的集合中同时包含数组ninjas与samurai中的所有元素。
assert(warriors.has("Kuma"),"Kuma is here");
assert(warriors.has("Hattori"),"And Hattori");
assert(warriors.has("Yagyu"),"And Yagyu");
assert(warriors.has("Oda"),"And Oda");
assert(warriors.has("Tomoe"),"Tomoe, last but not least");
//集合中没有重复的元素,虽然在两个数组中都存在Hattori,但是并集中只有一个
assert(warriros.size ===5,"There are 5 warriors in total");
</script>
</html>
首先创建两个数组ninjas与samurai,两个数组中都具有Hattori元素。假设我们同时需要两个数组中的元素,因此,我们创建一个新的Set,同时包含ninjas与samurai两个数组中的元素。虽然在两个数组中都存在Hattori元素,
但是我们希望在集合中只有一个Hattori元素。在本例中Set是最完美的、不需要手动判断元素已存在:Set会自动处理。