javascript tips - assign uniqueness to elements

本文介绍了一种确保数组元素唯一性的技术,包括代码实现和测试案例,展示了如何通过为每个元素分配唯一ID来避免重复项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

It is a common practice to make sure that each element of an array or an collection should be unqiue, application scenario including in the divide and conquer step, you may want to merge some array from different sub-step but you want to make sure no duplicate ends up in the list. 

 

below shows the code and test code to show you a common technique to make that happen.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="../unit.js"></script>
    <style type="text/css">
      #results li.pass {color:Green}
      #results li.fail {color:Red}
    </style>
</head>
<body>
<div id="test">
  <b>Hello</b>, I'm a ninja
</div>
<div id="test2"></div>
<script type="text/javascript">

  (function () {
    var run = 0;
    this.unique = function (array) {
      var ret = [];
      run++;
      for (var i = 0, length = array.length; i < length; i++) {
        var elem = array[i];

        if (elem.uniqueID !== run) {
          elem.uniqueID = run;
          ret.push(array[i]);
        }
      }
      return ret;
    };
  })();

  window.onload = function () {
    test("Test filter uniqueness", function () {
      var divs2 = document.getElementsByTagName("div");
      var divs = unique(document.getElementsByTagName("div"));
      assert(divs.length === 2, "No duplicates removed.");

      var body = unique([document.body, document.body]);
      assert(body.length === 1, "Body duplicate removed.");
    });
  };
</script>

<ul id="results"></ul>
</body>
</html>
 

the solution is basically assign some property to an element, and check if the new testing element has the matching unique id, if not, reassign the uniqueID; and the key is function will use a different ID each time the method to remove duplicate is called. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值