JavaScript 中 _.union() 方法的重要性是什麼?


_.union()

_.Union() 方法屬於 underscore.js 一個 javascript 庫。 _.union() 函式用於獲取多個數組並返回一個數組,其中包含所有這些陣列中唯一的術語(所有陣列的並集)。它會逐個檢查陣列中的每個值,並將唯一值推入另一個數組。

語法

_.union( array1, array2, .... );

示例

在以下示例中,使用 _.union() 來獲取唯一元素的陣列。

現場演示

<html>
<body>
<script 
   src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
   document.write(_.union([1, 2, 9, 40],
                          [1, 20, 3, 2],
                          [9, 2]));
</script>
</body>
</html>

輸出

1,2,9,40,20,3


陣列不僅可以包含數字或字串,還可以包含空字串或假值。 

示例

在以下示例中,陣列中使用了所有型別的值。儘管如此, _.union() 已經完成了其任務,即給出了一個包含唯一值的新陣列。

現場演示

<html>
<body>
<script 
   src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" >
</script>
</head>
<body>
<script type="text/javascript">
   document.write(_.union(["hello",2, "hi", 1, ""],  
                          ['the', undefined],  
                          ['', null],  
                          ["*", ""]));
</script>
</body>
</html>

輸出

hello,2,hi,1,,the,,,*

更新於:2019-07-30

1K+ 瀏覽量

開啟你的 職業

透過完成課程認證

開始
廣告
© . All rights reserved.