This time I will bring you JSCommon functionsSummary and summary, what are the precautions when using JS common functions, the following is a practical case, let’s take a look.
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 [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, continue to return 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.
nbsp;html> <style> #container{text-align: center; color: #333; font-size: 30px;} </style> <p></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>
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 <p style="text-align: left;">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. </p><h2 id="span-style-color-ff-strong-Throttling-strong-span"><span style="color: #ff0000"><strong>Throttling</strong></span></h2><p style="text-align: left;">Throttling means that no matter how it is triggered, it will be executed according to the specified interval. We also give a basic version. </p><pre class="brush:php;toolbar:false">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) // false
For basic types, return directly, for reference types, traverse recursion Call the clone method.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Vue documentation error-prone points sorting
##Detailed explanation of Angular CLI routing steps
The above is the detailed content of Summary of common JS functions. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
