_.union()方法在JavaScript中的重要性是什么?
_。联盟()
_.Union()方法属于 underscore.js的javascript库。 _.union()函数是用来取数组的n个,并用在所有这些数组中的唯一术语(所有数组的联合)返回一个新的数组。它检查数组的每个值,并将唯一值推入另一个数组。
语法
_.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,,,*