处理集合_key相等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>key相等</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>
const map = new Map();
//使用内置的location.href属性获取当前页面的URL.
const currentLocation = location.href;
//创建两个当前页面的连接
const firstLink = new URL(currentLocation);
const secondLink = new URL(currentLocation);
//分别为两个链接添加映射。
map.set(firstLink,{description:"firstLink"});
map.set(secondLink,{description:"secondLink"});
//尽管两个连接指向相同的值,但是仍然具有各自的映射。
assert(map.get(firstLink).description === "firstLink","First link mapping");
assert(map.get(secondLink).description === "secondLink","Second link mapping");
assert(map.size ===2,"There are two mappings!");
</script>
</html>
本例子中引入的js: test.js
在本例子中使用location.href属性获取当前页面的URL。然后URL构造函数创建两个URL当前页面连接的对象。接着每个链接对象关联描述信息。最后,检查映射是否正确创建。
两个不同的对象创建不同的映射,但是,两个url对象指向相同的URL地址:当前页面的地址。我们也会怀疑两个对象应该相等。但是,在javascript中,我们不能重载相等运算符,虽然两个对象的
内容相同,但是两个对象仍然不想等。这与其他语言不同,如java,C#等,要小心!。