Home > Article > Web Front-end > Summary of five common JavaScript functions
There are some issues in JavaScript that are often discussed. Everyone has different ideas on these issues. If you want to understand these issues, the best way is to implement them yourself. Not much to say. Say, Let’s get down to business. This article shares with you a summary of five common JavaScript functions. The content is quite good. I hope it can help friends in need.
There are many methods for array flattening, but in the end the best method is recursion to implement a flattening method with a specified depth, such a basic routine Everyone will understand.
function flattenDepth(array, depth = 1) { let result = [] array.forEach(item => { let d = depth if (Array.isArray(item) && d > 0) { result.push(...(flattenDepth(item, --d))) } else { result.push(item) } }) return result } console.log(flattenDepth([1, [2, [3, [4]], 5]])) // [ 1, 2, [ 3, [ 4 ] ], 5 ] console.log(flattenDepth([1, [2, [3, [4]], 5]], 2)) // [ 1, 2, 3, [ 4 ], 5 ] console.log(flattenDepth([1, [2, [3, [4]], 5]], 3)) // [ 1, 2, 3, 4, 5 ]
The recursive implementation is very simple and easy to understand. It is to traverse each item. If an item is an array, let the item continue to be called. Specified here depth is used as the depth of flattening. Because this parameter affects each item of the array, it is placed inside the loop.
The currying of functions has been talked about badly. Everyone has their own understanding and implementation method. The explanation in one sentence is execute when the parameters are enough. If there are not enough parameters, a function is returned, and the previous parameters are stored until there are enough.
function curry(func) { var l = func.length return function curried() { var args = [].slice.call(arguments) if(args.length < l) { return function() { var argsInner = [].slice.call(arguments) return curried.apply(this, args.concat(argsInner)) } } else { return func.apply(this, args) } } } var f = function(a, b, c) { return console.log([a, b, c]) }; var curried = curry(f) curried(1)(2)(3) // => [1, 2, 3] curried(1, 2)(3) // => [1, 2, 3] curried(1, 2, 3) // => [1, 2, 3]
It is not difficult to see from the above code. Each time the number of parameters is judged, it is compared with the number of curried function parameters. If it is less than the number, continue Return function, otherwise execute.
According to my understanding, anti-shake isNo matter how many times you trigger it, it will not trigger until a period of time you specify after the last trigger. Following this explanation, write a basic version.
function debounce(func, wait) { var timer return function() { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function() { func.apply(context, args) }, wait) } }
Now there is a requirement that it will be triggered at the beginning and the last time, and it can be configured. First, write a test page to facilitate testing the function. Every time Pressing the space bar once will increase the number by 1 to test the anti-shake and throttling functions.
<!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <style> #container{text-align: center; color: #333; font-size: 30px;} </style> </head> <body> <p id="container"></p> <script> var count = 1 var container = document.getElementById('container') function getUserAction(e) { // 空格 if (e.keyCode === 32) { container.innerHTML = count++ } } // document.onkeydown = debounce(getUserAction, 1000, false, true) document.onkeydown = throttle(getUserAction, 1000, true, true) function debounce(func, wait, leading, trailing) {} function throttle(func, wait, leading, trailing) {} </script> </body> </html>
The two parameters leading and trailing are used to determine whether the start and end are executed. If leading is true, it will be executed every time the space is pressed. If trailing If true, the last trigger will be executed every time it ends. Anti-shake function distance, if both are true, pressing space for the first time will add 1, and then pressing space quickly, the getUserAction inside will not be executed at this time, but will be executed after letting go. Add trailing to false , it will not be executed after letting go.
function debounce(func, wait, leading, trailing) { var timer, lastCall = 0, flag = true return function() { var context = this var args = arguments var now = + new Date() if (now - lastCall < wait) { flag = false lastCall = now } else { flag = true } if (leading && flag) { lastCall = now return func.apply(context, args) } if (trailing) { clearTimeout(timer) timer = setTimeout(function() { flag = true func.apply(context, args) }, wait) } } }
解释一下,每次记录上次调用的时间,与现在的时间对比,小于间隔的话,第一次执行后之后就不会执行,大于间隔或在间隔时间后调用了,则重置 flag,可以与上面那个基本版的对比着看。
节流就是,不管怎么触发,都是按照指定的间隔来执行,同样给个基本版。
function throttle(func, wait) { var timer return function() { var context = this var args = arguments if (!timer) { timer = setTimeout(function () { timer = null func.apply(context, args) }, wait) } } }
同样和防抖函数一样加上两个参数,也可使用上面的例子来测试,其实两者的代码很类似。
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 方法。
其实对于上面这些方法,总的来说思路就是递归和高阶函数的使用,其中就有关于闭包的使用,前端就爱问这些问题,最好就是自己实现一遍,这样有助于理解。
The above is the detailed content of Summary of five common JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!