一..扁平化数组
Array.prototype.flat()
用于将嵌套的数组扁平化,变成一维的数组。该方法返回一个新数组,对原数据没有影响。- 不传参数时,默认扁平化一层,可以传入一个整数,表示想要扁平化的层数。
- 传入
<=0
的整数将返回原数组,不扁平化 Infinity
关键字作为参数时,无论多少层嵌套,都会转为一维数组- 如果原数组有空位,
Array.prototype.flat()
会跳过空位。
1. 利用 数组的 reduce 方法;
function flat( arr,depth){
return depth>0 ? arr.reduce((acc,cur)=>{
if (Array.isArray(cur)){
return [...acc,...flat(cur,depth-1)]
}
return [...acc,cur];
},[]):arr
}
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];
flat(test,1)
// ["a", "b", "c", "d", Array(2), "g"]
// 变形题目考察原型方法, 编写test.flatDeep(depth)
Array.prototype.flatDeep=function(depth){
return depth>0 ? this.reduce((acc,cur)=>{
if (Array.isArray(cur)){
return [...acc,...cur.flatDeep(depth-1)]
}
return [...acc,cur];
},[]):arr
}
test.flatDeep(1)//
二 数组去重
1. es6 方法
function unique(arr){
return Array.from(new Set(arr))
// return [...new Set(arr)]
}
2. 利用hash 表 reduce 方法封装 数组元素n 时间复杂度O(n), 空间复杂度O(n)
function unique (arr){
const map=new Map();
return arr.reduce((acc,cur)=>{
if(!map.has(cur)){
map.set(cur,cur);
acc.push(cur);
}
return acc ;
},[])
}
var test = [1 ,'1',0,NaN,null,undefined,null ];
unique(test);
// [1, "1", 0, NaN, null, undefined]
3. 函数组合compose ;
const compose = (...fns)=>(args)=>fns.reduceRight((acc,cur)=>cur(acc),args);
// 形成一个由右到左执行的函数流;
如果希望函数从左向右执行;
// const compose = (...fns)=>(args)=>fns.reduce((acc,cur)=>acc(cur),args);
4. 函数柯里化
const curry =(fn)=>(...args)=>arg.length===fn.length?fn.call(null,...args):fn.bind(null,...args);
5.实现new 关键字
function _new(fn,...rest){
const tempObj = Object.create(fn.prototype);
const fnResult = fn.call(tempObj,...rest);
return fnResult instanceof Object ? fnResult : tempObj
}
6. 实现es 5 继承
function ParentFn(name,age){
this.color='red'
this.name=name;
}
ParentFn.prototype.sayName= function(){
console.log(this.name);
}
function ChildFn(parentName,childName){
ParentFn.call(this, parentName);
this.childName = childName;
}
ChildFn.prototype=Object.create(ParentFn.protoType);
ChildFn.prototype.constructor= ChildFn;
7. 实现数组的map方法;(回调函数的this)
Array.prototype.myMap=function(fn,context){
const arr=Array.prototype.slice(this);
const mapResult = [];
for(let i =0;i<arr.length;i++){
mapResult.push(fn.call(context,arr[i],i,this));
}
return mapResult;
}