返回值:ArrayjQuery.unique(array)

对 DOM 元素数组进行排序,并删除重复的元素。注意,该方法只能应用于 DOM 元素数组,无法在字符串数组或数字数组上使用。

$.unique() 函数会遍历对象数组,对其进行排序,并移除任何重复的节点。该函数只能应用在纯 JavaScript DOM 元素数组上,并且主要在 jQuery 内部使用。

从 jQuery 1.4 开始,该函数返回的结果数组中的元素位置,始终和它们在文档中的顺序一致。

示例:

移除 div 数组中任何重复的元素。

<!DOCTYPE html>
<html>
<head>
<style>
  div { color:blue; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<div>There are 6 divs in this document.</div>
  <div></div>
  <div class="dup"></div>
  <div class="dup"></div>

  <div class="dup"></div>
  <div></div>

<script>



    var divs = $("div").get(); // unique() must take a native array

    // add 3 elements of class dup too (they are divs)
    divs = divs.concat($(".dup").get());
    $("div:eq(1)").text("Pre-unique there are " + divs.length + " elements.");

    divs = jQuery.unique(divs);
    $("div:eq(2)").text("Post-unique there are " + divs.length + " elements.")
                  .css("color", "red");



</script>
</body>
</html>

演示: