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;
}
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
alert(arr.unique3());
那么如何拿到数组中的每一项呢?结合前面学习的es6各种for循环实质都是对数组的遍历
方法一 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))