如何在 JavaScript 中為每個物件建立一個唯一的 ID?


以下程式碼可為每個物件建立一個唯一的 ID:

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Create a unique ID for each object</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button&g;
<h3>Click on the above button to check if id generated are unique or not</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj = {
      id: Symbol("UID"),
      a: 22,
      b: 44,
   };
   let obj1 = {
      id: Symbol("UID"),
      a: 12,
      b: 41,
   };
   BtnEle.addEventListener("click", () => {
      if (obj.id === obj1.id) {
         resEle.innerHTML = "The id generated are not unique <br>";
      }
      else {
         resEle.innerHTML = "The id generated is unique for each object";
      }
   });
</script>
</body>
</html>

輸出

以上程式碼將生成以下輸出:

點選“單擊此按鈕”按鈕後:

更新於: 2020 年 7 月 21 日

1000+ 次觀看

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告