1.数组扁平化
面试中数组扁平化通常有两种版本,90%的公司都要求实现扁平化成一维数组,而10%的公司会要求扁平化到指定层
扁平化到一维
arr=[1,2,[3],[4,[5]]]的结果[1,2,3,4,5]
const merge = (arr) => {
let res = []
const main = (node) => {
node.forEach(element => {
if(!Array.isArray(element)) res.push(element)
else main(element)
});
}
main(arr)
return res
}
扁平化指定层数
arr=[1,2,[3],[4,[5]]]的扁平两次结果[1,2,3,4,[5]]
const merge = (arr,count) => {
let res = []
const main = (node,num) => {
if(num===1) {
res.push(...node)
return
}
node.forEach(element => {
if(!Array.isArray(element)) res.push(element)
else main(element,num-1)
});
}
main(arr,count)
return res
}
2.map
Array.prototype.map = function(callback) {
let len = this.length
let res = []
for(let i=0;i<len;i++) {
res.push(callback(this[i],i))
}
return res
}
3.filter
Array.prototype.filter = function(callback) {
let len = this.length
let res = []
for(let i=0;i<len;i++) {
if(callback(this[i],i))
res.push(this[i])
}
return res
}
4.reduce
Array.prototype.reduce = function(callback,begin) {
let len = this.length
for(let i=0;i<len;i++) {
if(!begin) {
begin = callback(this[i],this[i+1],i+1,this)
i++
} else {
begin = callback(begin,this[i],i,this)
}
}
return begin
}
5.使用reduce实现map(字节真题)
Array.prototype.map = function(callback) {
return this.reduce((begin,val)=>{
begin.push(callback(val))
return begin
},[])
}
6.forEach
Array.prototype.forEach = function(callback) {
let len = this.length
for(let i=0;i<len;i++)
callback(this[i],i)
}
7.instanceof
function myInstanceof (obj,Target) {
let __proto = obj.__proto__
while(__proto) {
if(__proto === Target.prototype) return true
__proto = __proto.__proto__
}
return false
}
//测试代码
function People (name) {
this.name = name
}
let p = new People("dzp")
console.log(myInstanceof(p,People))//true
8.apply
Function.prototype.apply = function(o,args=[]) {
o = o || window
let key = Symbol()
o[key] = this
let res = o[key](...args)
delete o[key]
return res
}
//测试
function fn () {
console.log(this.age)
}
let obj = {age:22}
fn.apply(obj)
9.call
Function.prototype.call = function(o,...args) {
o = o || window
let key = Symbol()
o[key] = this
let res = o[key](...args)
delete o[key]
return res
}
//测试
function fn () {
console.log(this.age)
}
let obj = {age:22}
fn.call(obj)
10.bind
Function.prototype.bind = function(o,...args) {
o = o || window
let key = Symbol()
o[key] = this
return ()=>{
return o[key](...args)
}
}
//测试
function fn () {
console.log(this.age)
}
let obj = {age:22}
fn.bind(obj)()