indexOf方法返回给定元素在数组中第一次出现的位置,返回结果是匹配开始的位置。如果没有出现则返回-1
var arr = [1,1,2,2,3,3,4,4];
var newArr = [];
for(var i=0,len=arr.length;i<len;i++){
if(newArr.indexOf(arr[i]) == -1){
newArr.push(arr[i]);
}
}
console.log(newArr);
function noRepeat(arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
res.lastIndexOf(arr[i]) !== -1 ? '' : res.push(arr[i]);
}
return res;
}
console.log(noRepeat([1, 1, 2, 2, 3, 3, 4, 4]));
var arr = [1,1,2,2,3,3,4,4];
var newArr = arr.filter(function(value,index,self){
return self.indexOf(value) === index;
});
console.log(newArr)
var arr = [1,1,2,2,3,3,4,4];
function noRepeat(arr){
var newArr = [];
var myset = new Set(arr);
for(var val of myset){
newArr.push(val);
}
return newArr;
}
var arr2 = noRepeat(arr);
console.log(arr2)
var arr = [1,1,2,2,3,3,4,4];
function norepeat(arr) {
let set = new Set(arr);
arr = [...set];
return arr;
}
console.log(norepeat(arr))
var arr = [1,2,2,2,3,3,4,4];
var newArr = Array.from(new Set(arr));
console.log(newArr);
var arr = [1,1,2,2,3,3,4,4];
function noRepeat(arr){
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[i] == arr[j] && i != j) {
arr.splice(j, 1);
}
}
}
return arr;
}
var arr2 = noRepeat(arr);
console.log(arr2)
function noRepeat(arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (!newArr.includes(arr[i])) {
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(noRepeat([1,1,2,2,3,3,4,4]))
function noRepeat(arr) {
var newArr = [];
arr.forEach(item => {
return newArr.includes(item) ? '' : newArr.push(item)
});
return newArr;
}
console.log(noRepeat([1,1,2,2,3,3,4,4]));
var arr = [1,1,2,2,3,3,4,4];
var obj={};
var newArr=[];
for(var i=0;i<arr.length;i++){
if(!obj[arr[i]]){
obj[arr[i]]=true;
newArr.push(arr[i]);
}
}
console.log(newArr);
var arr = [1,1,2,2,3,3,4,4];
function noRepeat(arr) {
var ret = [];
arr.sort();
var res = arr[0];
ret.push(arr[0]);
for (var i = 1; i < arr.length; i++) {
if (arr[i] != res) {
ret.push(arr[i]);
res = arr[i];
}
}
return ret;
}
var arr2 = noRepeat(arr);
console.log(arr2);
上一篇