本文實例講述了JavaScript移除數組內重復元素的方法。分享給大家供大家參考。具體分析如下:
這段JS代碼用於從數組中移除重復的元素,比如: ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'] 去重後返回:s ['apple', 'orange', 'peach', 'strawberry']
代碼如下:function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];
下面的代碼可以在浏覽器中驗證
代碼如下:Remove duplicate elements from an array. <br>
<pre> var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
</pre>
Note 'orange' is duplicate in fruits array. Click to remove duplicate elements from fruits array:<br>
<button onclick="check()">Remove Duplicate</button>
<script>
function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function check() {
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
alert(uniquefruits);
}
</script>
希望本文所述對大家的javascript程序設計有所幫助。