[仅个人学习使用]
js 数组去重
1.for 嵌套 for + splice
var DeWeight = function(nums) {
for(let i =0; i <nums.length-1; i++) {
for(let j = i +1; j <nums.length;j++) {
if(nums[i] === nums[j]) {
nums.splice(j,1)
j--
}
}
}
return nums
}
2.1.遍历 + indexof + push
var DeWeight = function(nums) {
var nums_push = []
for(let i=0; i <nums.length;i++) {
if(nums_push.indexOf(nums[i]) == -1) {
nums_push.push(nums[i])
}
}
return nums_push
}
2.2.forEach遍历 + indexof + push + 三行式
var DeWeight = function(nums) {
var nums_push = []
nums.forEach(item => {
nums_push.indexOf(item) == -1? nums_push.push(item):nums_push
});
return nums_push
}
3.利用js的filter方法
var DeWeight = function(nums) {
return nums.filter(function(item, index) {
// indexOf 返回的值 是第一个index
//比如[1,1,1] 中 indexof([1,1,1]) 每一次都返回0
//当返回第一个的index ==目前的index时 这是就目前来说第一次出现
return nums.indexOf(item) == index;
});
}
利用es6 Set方法实现去重
var DeWeight = function(nums) {
return Array.from(new Set(nums))
}