DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> 高效率去掉js數組中重復項的方法
高效率去掉js數組中重復項的方法
編輯:JavaScript基礎知識     
Array類型並沒有提供去重復的方法,如果要把數組的重復元素干掉,那得自己想辦法。

這是一個高效率去除重復的方法:
function hovercUnique(arr) {
var result = [], hash = {};
for (var i = 0, elem; (elem = arr[i]) != null; i++) {
if (!hash[elem]) {
result.push(elem);
hash[elem] = true;
}
}
return result;
//http://hovertree.com
}

使用例子效果:
http://hovertree.com/texiao/jsstudy/4/

http://hovertree.com/code/dev/lg17a37a.htm

使用方法:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>高效率去掉js數組中重復項的特效 - 何問起</title><base target="_blank" />
<meta charset="utf-8" />
<style>a{color:deeppink;}</style>
</head>
<body>
<div><a href="http://hovertree.com/">首頁</a> <a href="http://hovertree.com/texiao/">特效</a> <a href="http://hovertree.com/h/bjaf/ovjl4eus.htm">原文</a>
</div>
<div>
<script>
var h_hewenqiArray = new Array();
h_hewenqiArray[0] = "hovertree";
h_hewenqiArray[1] = "easysector";
h_hewenqiArray[2] = "hovertree";
h_hewenqiArray[3] = "keleyi";
h_hewenqiArray[4] = "keleyi";
h_hewenqiArray[5] = "何問起";
h_hewenqiArray[6] = "hovertree";
h_hewenqiArray[7] = "hoverclock";
h_hewenqiArray[8] = "yestop";
h_hewenqiArray[9] = 163;
h_hewenqiArray[10] = "何問起";
h_hewenqiArray[11] = 163;
h_hewenqiArray[12] = "hoverclock";
h_hewenqiArray[13] = "何問起";

var h_arrayLength = h_hewenqiArray.length;
document.write("原始數組元素個數:"+h_arrayLength + "<br />");
for (var i = 0; i < h_arrayLength; i++)
{
document.write(h_hewenqiArray[i]+"<br />");
}


function hovercUnique(arr) {
var result = [], hash = {};
for (var i = 0, elem; (elem = arr[i]) != null; i++) {
if (!hash[elem]) {
result.push(elem);
hash[elem] = true;
}
}
return result;
//http://hovertree.com
}

var h_hewenqiResult = hovercUnique(h_hewenqiArray);

var h_resultLength = h_hewenqiResult.length;
document.write("<br />去重復後數組元素個數:" + h_resultLength + "<br />");
for (var i = 0; i < h_resultLength; i++) {
document.write(h_hewenqiResult[i] + "<br />");
}
</script>
</div>
<div style="border:solid 1px silver"><p>何問起 hovertree.com</p></div>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved