前端常用功能实现总结(1)

拷贝:

1·浅拷贝

.1)直接利用es6中的拓展运算

const obj = {
    xxx:xxx,
    xxx:xxx
}
const targetObj = {...obj}

.2)Object.assign()

const obj = {
    xxx:xxx,
    xxx:xxx
}

const targetObj = Object.asign({},obj)

.3)Object.create()

const obj = {
    xxx:xxx,
    xxx:xxx
}
const targetObj = Object.create(obj,Object.getOwnPropertyDescriptors(obj))

等方法

2.深拷贝:整体思路(递归实现,其他实现)

.1)通过JSON转换(无法对function, undefind, symbol等进行处理,且存在边界问题)

const obj = {
	xxx:xxx,
	xxx:xxx
}
const targetObj = JSON.parse(JSON.stringify(obj))

.2)递归实现

function deepClone(obj) {

	if ([null, undefined, NaN, false].includes(obj)) return obj
	if (typeof obj !== 'object' && typeof obj !== 'function') {
		return obj
	}

	const res = Object.prototype.toString.call(obj) === '[object Array]' ? [] : {}
	for (const i in obj) {
		if (obj.hasOwnProperty(i)) {
			res[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
		}
	}
	return res
}

节流防抖:(方法不唯一)

防抖实现

let timeout = null
function debounce(func, wait = 400) {
    if (timeout !== null) clearTimeout(timeout)
        timeout = setTimeout(() => {
            typeof func === 'function' && func()
    }, wait)
}

节流实现

let timer, flag;
function throttle(func, wait = 400) {
if (!flag) {
        flag = true
        timer = setTimeout(() => {
            flag = false
            typeof func === 'function' && func()
        }, wait)
    }
}

以上方法均不唯一,提供一个解决方案,提供分思路为主奥

数组去重问题:

1·利用es6 Set 进行去重,但是目标 范围有限
const arr1= [...new Set(arr)]
//以及
const arr1= Array.from(new Set(arr))


2·利用indexOf结合过滤去重
const arr1= arr.filter((item, index) => arr.indexOf(item) === index)

3.利用includes+遍历处理
function deWeight(arr){
    let res = []
    arr.forEach(item=>{
      if(!arr1.includes(item)){
		res.push(item)
	    }
    })
    return res
}
4.较为复杂的数据格式时可直接使用for进行深层对比即可

这次先写到这里,以后在继续慢慢写其他的QAQ

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值