Five common JavaScript functions
JS function issues are often discussed in JavaScript front-end development. This issue is a matter of different opinions. The following is an introduction to the five common functions of JS through sample code. Friends who are interested can take a look.
There are some issues in JavaScript that are frequently discussed. Everyone has different ideas about these issues. If you want to understand these issues, the best way is to implement them yourself. Without further ado, let’s get down to the topic.
Array flattening
There are many methods for array flattening, but in the end the best method is recursion to achieve a specified depth of flattening Method, so that you will understand the basic routines.
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, that is, traversing each item. If an item is an array, let the item continue to be called. Depth is specified here as the flattening depth, because this parameter is important for the array. Every item of has a role to play, so it is placed inside the loop.
Currying
Currying of functions has been talked about badly. Everyone has their own understanding and implementation method. In one sentence The explanation is that if there are enough parameters, it will be executed. If there are not enough parameters, a function will be returned. The previous parameters will be 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 that 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, it will continue to return to the function, otherwise it will be executed.
Anti-shake
According to my understanding, anti-shake means that no matter how many times you trigger it, it will wait until a period of time you specify after the last trigger. Time is triggered. 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. Each time you press the space bar, the number will increase by 1. Test debounce 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>Determine whether the start and end are executed through the two parameters leading and trailing. If leading is true, it will be executed once every time you press space. If trailing is true, the last trigger will be triggered every time you end. implement. 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)
}
}
}Explain, each time the time of the last call is recorded, compare it with the current time. If it is less than the interval, it will not be executed after the first execution. If it is greater than the interval or called after the interval, Then reset the flag and compare it with the basic version above.
Throttling
Throttling means that no matter how it is triggered, it will be executed according to the specified interval. We also give a basic version.
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)
}
}
}It also adds two parameters like the anti-shake function. You can also use the above example to test. In fact, the codes of the two are very similar.
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
}
}
}Object copy
We all know that object copy is divided into deep copy and shallow copy. The black technology method is to use
JSON.parse(JSON.stringify(obj))
Another way is to use recursion
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) // falseFor basic types, return directly, for reference types, traverse recursion Call the clone method.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Introduction to time-sharing functions for javascript performance optimization
E-mail address format verification in JavaScript
How to introduce icon icon into Vue project
The above is the detailed content of Five common JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1384
52
Tips for dynamically creating new functions in golang functions
Apr 25, 2024 pm 02:39 PM
Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.
Considerations for parameter order in C++ function naming
Apr 24, 2024 pm 04:21 PM
In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.
How to write efficient and maintainable functions in Java?
Apr 24, 2024 am 11:33 AM
The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.
Complete collection of excel function formulas
May 07, 2024 pm 12:04 PM
1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.
Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters
Apr 21, 2024 am 10:21 AM
The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.
What are the benefits of C++ functions returning reference types?
Apr 20, 2024 pm 09:12 PM
The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.
What is the difference between custom PHP functions and predefined functions?
Apr 22, 2024 pm 02:21 PM
The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.
C++ Function Exception Advanced: Customized Error Handling
May 01, 2024 pm 06:39 PM
Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.


