深拷贝
方法一
// 深拷贝
deepCopy(obj){
let str, newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
} else if(window.JSON){
str = JSON.stringify(obj), //系列化对象
newobj = JSON.parse(str); //还原
} else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
},
方法二
export function deepClone (obj: Object | any) {
let result: any = {}
for (let k in obj) {
let typeStr = Object.prototype.toString.call(obj[k])
.match(/\[object (.*?)\]/)[1].toLowerCase();
switch (typeStr) {
case 'object':
result[k] = deepClone(obj[k])
break
case 'array':
result[k] = obj[k].slice()
break
default:
result[k] = obj[k]
}
}
return result
}
数组去重
方法一
removal(array){
var res = [];
for (var i = 0, len = array.length; i < len; i++) {
var current = array[i];
if (res.indexOf(current) === -1) {
res.push(current)
}
}
return res;
// 舍弃ES6
// return new Set(arr);
},
方法二
export function uniqueArray(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index)
}
console.log(uniqueArray([1, 2, 3, 2, 1, 3, 4, 5, 6, 3, 8]))
// [1, 2, 3, 4, 5, 6, 8]
方法三
export function uniqueArray(arr) {
const newArr = arr.sort()
let result = [newArr[0]]
for (let i = 1; i < newArr.length; i++) {
newArr[i] !== newArr[i - 1] && result.push(newArr[i])
}
return result
}
console.log(uniqueArray([1, 2, 3, 2, 1, 3, 4, 5, 6, 3, 8]))
// [1, 2, 3, 4, 5, 6, 8]
方法四 set方法
set是ES6中一种新的数据结构,它本身是一个构造函数,类似数组,但他的成员值都是唯一的,无重复的值利用这一点可以实现数组去重
//数组去重
[...new Set(arr)]
//by the way--->字符串去重
[...new Set(str)].join('');
方法五 数组对象去重
let arr = [
{
name:"lilei",
age:14,
},
{
name:"hanmeimei",
age:15,
},
{
name:"bob",
age:14,
}
]
uniqueArray(arr,param) {
console.log(arr,'arr')
if (Array.isArray(arr)) {
let temp = [];
let newArr = arr.reduce((acc, cur) => {
if (temp.indexOf(cur[param]) === -1) {
temp.push(cur[param]);
acc.push(cur);
return acc;
} else {
console.log(acc);
return acc;
}
}, []);
// 可以用别的方法判断是否有重复,毕竟已经把重复的项过滤掉了
let isDuplicate = newArr.length === arr.length;
return newArr
}
},
uniqueArray(arr,'age')