JavaScript 五大常见函数(2)

function throttle(func, wait, leading, trailing) { var timer, lastCall = 0, flag = true return function() { var context = this var args = arguments var now = + new Date() flag = now - lastCall > wait if (leading && flag) { lastCall = now return func.apply(context, args) } if (!timer && trailing && !(flag && leading)) { timer = setTimeout(function () { timer = null lastCall = + new Date() func.apply(context, args) }, wait) } else { lastCall = now } } }

对象拷贝

对象拷贝都知道分为深拷贝和浅拷贝,黑科技手段就是使用

JSON.parse(JSON.stringify(obj))

还有个方法就是使用递归了

function clone(value, isDeep) { if (value === null) return null if (typeof value !== 'object') return value if (Array.isArray(value)) { if (isDeep) { return value.map(item => clone(item, true)) } return [].concat(value) } else { if (isDeep) { var obj = {} Object.keys(value).forEach(item => { obj[item] = clone(value[item], true) }) return obj } return { ...value } } } var objects = { c: { 'a': 1, e: [1, {f: 2}] }, d: { 'b': 2 } } var shallow = clone(objects, true) console.log(shallow.c.e[1]) // { f: 2 } console.log(shallow.c === objects.c) // false console.log(shallow.d === objects.d) // false console.log(shallow === objects) // false

对于基本类型直接返回,对于引用类型,遍历递归调用 clone 方法。

总结

其实对于上面这些方法,总的来说思路就是递归和高阶函数的使用,其中就有关于闭包的使用,前端就爱问这些问题,最好就是自己实现一遍,这样有助于理解。希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxjgd.html