Array.prototype.unique3 = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){//可以看出只要能拿到數(shù)組中的每一項問題就可以解決
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
alert(arr.unique3());
那么如何拿到數(shù)組中的每一項呢耍鬓?結(jié)合前面學(xué)習(xí)的es6各種for循環(huán)實質(zhì)都是對數(shù)組的遍歷
方法一 for-0f
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1']
var a=[]
var b={}
for(let i of arr){
if (!b[i]) {
b[i]=1
a.push(i)
}
}
alert(a)
forEach
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1']
var a=[]
var b={}
arr.forEach(i=>{
if (!b[i]) {
b[i]=1
a.push(i)
}
})
alert(a)
封裝
forEach
var arr1 = [112,112,34,'你好',112,112,34,'你好','str','str1']
var a=[]
var b={}
function aaa(arr){
arr.forEach(i=>{
if (!b[i]) {
b[i]=1
a.push(i)
}
})
return a
}
alert(aaa(arr1))