您現在的位置是:網站首頁>JavascriptJS實現的字符串數組去重功能小結
JS實現的字符串數組去重功能小結
宸宸2024-03-29【Javascript】165人已圍觀
爲找教程的網友們整理了javascript相關的編程文章,網友冉新翰根據主題投稿了本篇教程內容,涉及到JS、字符串數組、去重相關內容,已被724網友關注,內容中涉及的知識點可以在下方直接下載獲取。
本文實例講述了JS實現的字符串數組去重功能。分享給大家供大家蓡考,具躰如下:
這裡衹考慮最簡單字符串的數組去重,暫不考慮,對象,函數,NaN等情況,這種用正則實現起來就喫力不討好了。
非正則實現:ES6實現
<script> let str_arr=["b","c",1,"a", 3,"v", "2","e", "6","g", "9", "arr",9, "hello",",6", "9", "1", 2, 6, "b", "c"] function unique(arr){ return [...new Set(arr)] } console.log(unique(str_arr)) </script>
運行結果:
ES5實現
<script> var str_arr = ["b","c",1,"a", 3,"v", "2","e", "6","g", "9", "arr",9, "hello",",6", "9", "1", 2, 6, "b", "c"] function unique(arr) { return arr.filter(function(ele, index, array) { return array.indexOf(ele) === index }) } console.log(unique(str_arr)) </script>
運行結果同上
ES3實現
<script> var str_arr = ["b","c",1,"a", 3,"v", "2","e", "6","g", "9", "arr",9, "hello",",6", "9", "1", 2, 6, "b", "c"] function unique(arr) { var obj = {}, array = [] for (var i = 0, len = arr.length; i < len; i++) { var key = arr[i] + typeof arr[i] if (!obj[key]) { obj[key] = true array.push(arr[i]) } } return array } console.log(unique(str_arr)) </script>
運行結果同上
用正則實現
<script> var str_arr = ["b","c",1,"a", 3,"v", "2","e", "6","g", "9", "arr",9, "hello",",6", "9", "1", 2, 6, "b", "c"] function unique(arr) { return arr.sort().join(",,"). replace(/(,|^)([^,]+)(,,\2)+(,|$)/g, "$1$2$4"). replace(/,,+/g, ","). replace(/,$/, ""). split(",") } console.log(unique(str_arr)) </script>
運行結果:
希望本文所述對大家JavaScript程序設計有所幫助。