<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
//最简单的数组去重
Array.prototype.unique1 = function(){
var res = [];
for(var i = 0; i<this.length;i++){
if(res.indexOf(this[i])==-1){
res.push(this[i]);
}
}
return res;
}
//以下该方法会改变数组的顺序,所以存在一定的局限性
Array.prototype.unique2 = function(){
this.sort();
for(var i = this.length-1; i>-1;i--){
if(this[i]==this[i-1]){
this.splice(i,1)
}
}
return this;
}
//速度最快, 占空间最多
Array.prototype.unique3 = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
//优化遍历
Array.prototype.unique4 = function(){
var res = [];
for(var i = 0,l = this.length; i<l;i++){
for(var j = i+1; j < l; j++){
if(this[i]==this[j]){
j = ++i;
}
}
res.push(this[i])
}
return res;
}
alert(arr.unique4());
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
//最简单的数组去重
Array.prototype.unique1 = function(){
var res = [];
for(var i = 0; i<this.length;i++){
if(res.indexOf(this[i])==-1){
res.push(this[i]);
}
}
return res;
}
//以下该方法会改变数组的顺序,所以存在一定的局限性
Array.prototype.unique2 = function(){
this.sort();
for(var i = this.length-1; i>-1;i--){
if(this[i]==this[i-1]){
this.splice(i,1)
}
}
return this;
}
//速度最快, 占空间最多
Array.prototype.unique3 = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
//优化遍历
Array.prototype.unique4 = function(){
var res = [];
for(var i = 0,l = this.length; i<l;i++){
for(var j = i+1; j < l; j++){
if(this[i]==this[j]){
j = ++i;
}
}
res.push(this[i])
}
return res;
}
alert(arr.unique4());
</script>
</head>
<body>
</body>
</html>