處理集合_key相等
阿新 • • 發佈:2020-12-04
<!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#等,要小心!。