Array.prototype.clearRepetitionB = function(){
var result = [];
for(var i=0; i<this.length; i++){
if(result.indexOf(this[i]) == -1){
result.push(this[i]);
}
}
return result;
}
//有了indexOf 方法不就可以根据检测到的每个元素的第一次出现时的索引和这个元素自身的索引值比较相等来判断是否重复
Array.prototype.clearRepetitionC = function(){
var result = [this[0]];
for(var i=1; i<this.length; i++){
if(this.indexOf(this[i]) == i){
result.push(this[i]);
}
}
return result;
}
Array.prototype.clearRepetitionD = function(){
var result = [];
var obj = {};
var key,type;
for(var i=0; i<this.length; i++){
key = this[i];
type = typeof key;
if(!obj[key]){
obj[key] = [type];
result.push(key);
}else if(obj[key].indexOf(type)){
obj[key].push(type);
result.push(key);
}
}
return result;
}
//数组中元素的顺序跟原始数组中元素的顺序不一样了
Array.prototype.clearRepetitionE = function(){
var result = [];
for(var i=0; i<this.length; i++){
for(var j=i+1; j<this.length; j++){
if(this[i] === this[j]){
j = ++i;
}
}
result.push(this[i]);
}
return result;
}
//先用数组的排序方法sort进行数组元素排序,然后再进行去重工作
Array.prototype.clearRepetitionF = function(){
this.sort();
var result = [this[0]];
for(var i=1; i<this.length; i++){
if(this[i] !== result[result.length-1]){
result.push(this[i]);
}
}
return result;
}
转载: https://www.jb51.net/article/74484.htm
网友评论