模拟new方法
function Otaku(name,age) {
this.name = name;
this.age = age;
this.habit = 'Games'
}
Otaku.prototype.strength = 60;
Otaku.prototype.sayName = function () {
console.log("I am " + this.name);
};
function myNew(fn, ...args) {
const obj = Object.create(fn.prototype);
const ret = fn.apply(obj, args);
return typeof ret === "object" ? ret || obj : obj;
}
const person = myNew(Otaku,'甲',20);
console.log(person,'person');
数组去重
function unique(arr) {
let sortArr = arr.sort()
return sortArr.reduce((acc, current) => {
if (acc[acc.length - 1] !== current) {
acc.push(current);
}
return acc;
}, [sortArr[0]]);
}
function unique1(arr) {
return arr.filter((element, index, array) => {
return array.indexOf(element) == index;
});
}
扁平化数组
const flattenArr = (arr) => {
return Array.isArray(arr)
? arr.reduce((prev,current) => {
return [...prev,...flattenArr(current)]
},[])
: [arr];
}
const newArr = flattenArr([[1,1],[2,3],12,32,[90]]);
console.log(newArr);