In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What are the practical JavaScript code snippets, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
1. Download an excel document
At the same time, it is suitable for documents that browsers such as word,ppt do not perform preview by default, and can also be used to download the stream data returned by the back-end interface, see 3
/ / download a link function download (link) Name) {if (! name) {name=link.slice (link.lastIndexOf ('/') + 1)} let eleLink = document.createElement ('a') eleLink.download = name eleLink.style.display = 'none' eleLink.href = link document.body.appendChild (eleLink) eleLink.click () document.body.removeChild (eleLink)} / / download exceldownload (' http://111.229.14.189/file/1.xlsx')2.) Customize and download some content in the browser
Scene: I want to download some DOM content, I want to download a JSON file
/ * * browser downloads static file * @ param {String} name file name * @ param {String} content file content * / function downloadFile (name Content) {if (typeof name = = 'undefined') {throw new Error (' The first parameter name is a must')} if (typeof content = = 'undefined') {throw new Error (' The second parameter content is am ust')} if (! (content instanceof Blob)) {content = new Blob ([content])} const link = URL.createObjectURL (content) download (link) Name)} / / download a link function download (link, name) {if (! name) {/ / if no name is provided Intercept the last block from the given Link: name = link.slice (link.lastIndexOf ('/') + 1)} let eleLink = document.createElement ('a') eleLink.download = name eleLink.style.display = 'none' eleLink.href = link document.body.appendChild (eleLink) eleLink.click () document.body.removeChild (eleLink)}
Mode of use:
DownloadFile ('1. Txtcalendar downloadFile') JSON. Stringify ({name:'hha'})) 3. Download the stream returned by the backend
The data is returned by the backend in the form of an interface. Call the download method in 1 to download it.
Download ('http://111.229.14.189/gk-api/util/download?file=1.jpg') download (' http://111.229.14.189/gk-api/util/download?file=1.mp4')4.) To provide a link to a picture, click to download
For pictures, pdf and other files, the browser will perform a preview by default and cannot call the download method to download. You need to first convert the pictures, pdf and other files into blob, and then call the download method to download them. The conversion method is to use axios to request the corresponding link.
/ / it can be used to download the file types that the browser previews by default. For example, import axios from 'axios'//, such as mp4,jpg, provides a link to download the file. The link can be http://xxx.com/xxx.xlsfunction downloadByLink (link,fileName) {axios.request ({url: link, responseType:' blob' / / key code). Let axios change the response to blob}) .then (res = > {const link=URL.createObjectURL (res.data) download (link, fileName)})}
Note: there will be restrictions on the same origin policy, and forwarding needs to be configured.
5 Anti-shaking
If a method is called multiple times at a certain interval, it will only be executed once.
The implementation of this method is copy from the Lodash library
/ * * @ param {*} func function to be debouce * @ param {*} wait waiting time. Whether the default 500ms * @ param {*} immediate immediately executes * / export function debounce (func, wait=500, immediate=false) {var timeout return function () {var context = this var args = arguments if (timeout) clearTimeout (timeout) if (immediate) {/ / if it has been executed Var callNow =! timeout timeout = setTimeout (function () {timeout = null}, wait) if (callNow) func.apply (context, args)} else {timeout = setTimeout (function () {func.apply (context, args)}, wait)}
Mode of use:
Document function onInput () {console.log ('1111')} const debounceOnInput = debounce (onInput) document .getElementById (' input') .addEventListener ('input', debounceOnInput) / / entered in Input. Multiple calls will only wait for 500ms to trigger once after the call ends.
If the third parameter immediate passes true, a call will be executed immediately. Subsequent calls will not be executed again, so you can try it in the code yourself.
6 throttling
Call the method multiple times and execute it at regular intervals
The implementation of this method is also copy from the Lodash library.
/ * throttling, triggered multiple times, execute * @ param {Function} func * @ param {Int} wait * @ param {Object} options * / export function throttle (func, wait=500, options) {/ / container.onmousemove = throttle (getUserAction, 1000) Var timeout, context, args var previous = 0 if (! options) options = {leading:false,trailing:true} var later = function () {previous = options.leading = = false? 0: new Date () .getTime () timeout = null func.apply (context Args) if (! timeout) context = args = null} var throttled = function () {var now = new Date (). GetTime () if (! previous & & options.leading = false) previous = now var remaining = wait-(now-previous) context = this args = arguments if (remaining wait) {if (timeout) { ClearTimeout (timeout) timeout = null} previous = now func.apply (context Args) if (! timeout) context = args = null} else if (! timeout & & options.trailing! = = false) {timeout = setTimeout (later, remaining)}} return throttled}
The third parameter is a little more complicated, options.
Leading, the function is called at the beginning of each wait delay, and the default value is false
Trailing, the function is called at the end of each wait delay, and the default value is true
You can set different effects according to different values:
Leading-false,trailing-true: by default, the function will not be called until the delay ends
Leading-true,trailing-true: called at the beginning of the delay and after the delay is over
Leading-true, trailing-false: called only at the beginning of delay
Example:
Document function onInput () {console.log ('1111')} const throttleOnInput = throttle (onInput) document. GetElementById (' input') .addEventListener ('input', throttleOnInput) / / enter in Input and execute code 7. CleanObject every 500ms
Remove the attribute with empty value (null,undefined,'') in the object, and take a chestnut:
Let res=cleanObject ({name:'', pageSize:10, page:1}) console.log ("res", res) / / enter {page:1,pageSize:10} name is an empty string and the attribute is deleted.
The usage scenario is: backend list query API. If the front end of a field is not passed, the back end will not filter based on that field. For example, if name is not passed, it will only filter based on page and pageSize. But when the front end queries parameters (vue or react), it is often defined in this way.
Export default {data () {return {query: {name:'', pageSize:10, page:1} const [query,setQuery] = useState ({name:'',page:1,pageSize:10})
When sending data to the backend, you need to determine whether an attribute is an empty string, and then spell parameters for the backend. This piece of logic is extracted as cleanObject. The code is implemented as follows
Export const isFalsy = (value) = > (value = 0? False:! value); export const isVoid = (value) = > value = undefined | | value = null | | value = "; export const cleanObject = (object) = > {/ / Object.assign ({}, object) if (! object) {return {};} const result = {... object}; Object.keys (result). ForEach (key) = > {const value = result [key]; if (isVoid (value)) {delete result [key];}}) Return result;}; let res=cleanObject ({name:'', pageSize:10, page:1}) console.log ("res", res) / / enter {page:1,pageSize:10} 8. Get the file suffix name
Use scenarios: upload files to determine suffix names
/ * * get the file suffix * @ param {String} filename * / export function getExt (filename) {if (typeof filename = = 'string') {return filename .split ('.') .pop () .toLowerCase ()} else {throw new Error ('filename must be a string type')}}
Mode of use
GetExt ("1.mp4") / /-> mp49. Copy content to clipboard export function copyToBoard (value) {const element = document.createElement ('textarea') document.body.appendChild (element) element.value = value element.select () if (document.execCommand (' copy')) {document.execCommand ('copy') document.body.removeChild (element) return true} document.body.removeChild (element) return false}
Mode of use:
/ / return truecopyToBoard ('lalallala') if replication is successful
Principle:
Create a textare element and call the select () method to select
Document.execCommand ('copy') method to copy the current selection to the clipboard.
10. How many milliseconds to sleep / * xxxms * @ param {Number} milliseconds * / export function sleep (ms) {return new Promise (resolve = > setTimeout (resolve, ms))} / / usage const fetchData=async () = > {await sleep (1000)} 11. Generate random string / * * generate random id * @ param {*} length * @ param {*} chars * / export function uuid (length, chars) {chars = chars | | '0123456789abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQSTUVWXYZ' length = length | 8 var result =' for (var I = length; I > 0;-- I) result + = chars [Math.floor (Math.random () * chars.length)] return result}
Mode of use
/ / the first parameter specifies the number of digits, and the second string specifies characters, all of which are optional. If none is passed, 8-bit uuid () is generated by default.
Usage scenario: used for the front end to generate random ID. After all, both Vue and React now need to bind key.
twelve。 Simple deep copy / * * deep copy * @ export * @ param {*} obj * @ returns * / export function deepCopy (obj) {if (typeof obj! = 'object') {return obj} if (obj = = null) {return obj} return JSON.parse (JSON.stringify (obj))}
Defect: copy only objects, arrays, and object arrays, which is sufficient for most scenes
Const person= {name:'xiaoming',child: {name:'Jack'}} deepCopy (person) / / new person13. Array deduplication / * Array deduplication * @ param {*} arr * / export function uniqueArray (arr) {if (! Array.isArray (arr)) {throw new Error ('The first parameter must be an array')} if (arr.length = = 1) {return arr} return [. New Set (arr)]}
The principle is to take advantage of the fact that there are no repeating elements in Set.
UniqueArray ([1, 1, 1, 1, 1) / / [1] 14. Object converted to FormData object / * object converted to formdata * @ param {Object} object * / export function getFormData (object) {const formData = new FormData () Object.keys (object) .forEach (key = > {const value = object [key] if (Array.isArray (value)) {value.forEach ((subValue, I) = > formData.append (key + `[${I}]` SubValue))} else {formData.append (key, object [key])}}) return formData}
Usage scenario: when uploading a file, we need to create a new FormData object, and then append as many parameters as there are. Using this function can simplify the logic.
Mode of use:
Let req= {file:xxx, userId:1, phone:'15198763636', / /...} fetch (getFormData (req)) 15. Leave it to n places after the decimal point / / keep a few places after the decimal point. Default is 2 digits export function cutNumber (number, no = 2) {if (typeof number! = 'number') {number = Number (number)} return Number (number.toFixed (no))}
Usage scenario: the floating point number of JS is too long, and sometimes the page needs to be displayed with 2 decimal places.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.