In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "what are the JS development skills", the content is easy to understand, clear, hope to help you solve your doubts, let the editor lead you to study and learn "what are the JS development skills" this article.
Common JS function
1. Time formatting
The time displayed in the interface is ever-changing, so the importance of a function that deals with time is self-evident.
Export function formatDate (oldDate, fmt) {let date = new Date () if (typeof oldDate = 'string' | | typeof oldDate =' number') {date = new Date (+ oldDate)} else {date = oldDate} if (/ (y +) / .test (fmt)) {fmt = fmt.replace (RegExp.$1, (date.getFullYear () +'). Substr (4-RegExp.$1.length))} let o = {'date.getFullYear ()): date.getMonth () + 1 : date.getDate (), 'hackers: date.getHours (),' masks: date.getMinutes (), 'sails: date.getSeconds ()} function padLeftZero (str) {return (' 00' + str) .substr (str.length)} for (let k in o) {if (new RegExp (`(${k})`) .test (fmt)) {let str = o [k] + 'fmt = fmt.replace (RegExp.$1) (RegExp.$1.length = 1)? Str: padLeftZero (str)} return fmt} copy the code
FormatDate accepts two parameters, and the oldDate type can be Date,String,Number. Because it's really convenient to use timestamps to pass time, and JS is a weakly typed language, I treat data of String and Number types as timestamps. Fmt is the type of format: yyyy-MM-dd hh:mm, where yyyy | MM | dd | hh | mm is the keyword matching year / month / day / hour / minute respectively. Among them, the hyphen can be replaced at will, and only the other keywords can be removed from the show. To give a few examples:
Yyyy MM month dd-> September 7, 2019
Hh minutes mm seconds-> 16 minutes 53 seconds
two。 Get the timestamp of the response in "days"
I usually get the time three days ago, less than 12 data, and less than 24 hours, so I have a function to get the timestamp on a daily basis.
Export function setDate (num) {return Date.now () + num * 24 * 60 * 60 * 1000} copy the code
If the time is positive, you can get the future time, and if the time is negative, you can get the past time. For instance
Time 12 hours ago-> setDate (- .5)
Time 24 hours ago-> setDate (- 1)
Time after three days-> setDate (3)
3. Get parameters in URL
It seems that there are not many applications of this requirement in the era of the three frameworks, but there are still a lot of questions in the interview, so it's good to know about it.
Simple implementation
Var urlParams = new URLSearchParams ('? post=1234&action=edit'); console.log (urlParams.get ('action')); / / "edit" copy the code
Take a look at the browser support is quite good, except for the evil ie
Complex implementation
Function getUrlParams (param) {/ / depends on the browser environment, and _ window.location.search is a browser function / / meaning: set or return from the question mark (?) The URL at the beginning (query section). Var query = _ window.location.search.substring (1); var vars = query.split ("&"); for (var iTunes 3)
GetUrlParams ('b')-> 5
GetUrlParams ('c')-> 8888
4. The mobile terminal determines the type of browser.
BrowserInfo = {isAndroid: Boolean (navigator.userAgent.match (/ android/ig)), isIphone: Boolean (navigator.userAgent.match (/ iphone | ipod/ig)), isIpad: Boolean (navigator.userAgent.match (/ ipad/ig)), isWeixin: Boolean (navigator.userAgent.match (/ MicroMessenger/ig)), isAli: Boolean (navigator.userAgent.match (/ AlipayClient/ig)), isPhone: Boolean (/ (iPhone | iPod | iOS | Android) / i.test (navigator.userAgent)} copy code
At present, it mainly supports Android & Apple & ipad & Wechat & Alipay & whether it is a mobile phone.
5. Array dimension reduction
Two-dimensional array
Let arr = [[1], [2], [3]] arr = Array.prototype.concat.apply ([], arr); / / [1,2,3] copy the code
Dimension reduction of multi-dimensional array
Let arr = [1,2, [3], [[4] arr = arr.flat (3) / / [1,2,3,4] copy the code
There is a compatibility problem with flat, but it is not a big problem on the mobile side. The browser side is not compatible with edge. Fill in Infinity to expand an array of arbitrary depth
6. Deep copy
Use the variable a to copy object b, and change the value of b in a, which is called shallow copy. To make an independent of b, you need a deep copy.
Simple treatment
Function deepClone () {return JSON.parse (JSON.stringify (obj))} copy the code
Since it is recommended processing, it has its shortcomings, the above is mainly the use of JSON serialization and deserialization. JSON does not support functions and undefined, so it will be missing in these cases, but it can already satisfy most of the cases.
Complex processing
Complex processing needs to be recursive.
Function deepClone (obj) {function isClass (o) {if (o = null) return "Null"; if (o = undefined) return "Undefined"; return Object.prototype.toString.call (o) .slice (8,-1);} var result; var oClass = isClass (obj); if (oClass = = "Object") {result = {};} else if (oClass = = "Array") {result = [];} else {return obj } for (var key in obj) {var copy = obj [key]; if (isClass (copy) = = "Object") {result [key] = arguments.callee (copy); / / Recursive call} else if (isClass (copy) = = "Array") {result [key] = arguments.callee (copy);} else {result [key] = obj [key];}} return result;} copy code
7. Anti-shaking & throttling
Anti-shaking and throttling are high-level skills, and the most common occasion in the business is to search for content change tips. Even if you don't add it, you may not be able to see the difference, but adding novice maintenance code may worship you.
Anti-shaking
Function debounce (func, wait) {let timeout; return function () {let context = this; let args = arguments; if (timeout) clearTimeout (timeout); timeout = setTimeout (() = > {func.apply (context, args)}, wait);}} copy the code
Throttling
Function throttle (func, wait) {let previous = 0; return function () {let now = Date.now (); let context = this; let args = arguments; if (now-previous > wait) {func.apply (context, args); previous = now;}} copy the code
8. Get the array extremum
Function smallest (array) {return Math.min.apply (Math, array);} function largest (array) {return Math.max.apply (Math, array);} smallest ([0,1,2.2,3.3]); / / 0largest ([0,1,2.2,3.3]); / / 3.3 copy code
Thank you for your comments over the years, and I would like to supplement the implementation of es6.
Let list = [1,2,3,4,5] Math.max (... list) / / 5Math.min (... list) / / 1 copy the code
9. Judge whether the decimals are equal or not
Function epsEqu {return Math.abs (x-y) < Math.pow (2,-53);} / / example 0.1 + 0.2 = 0.3 / / falseepsEuq (0.1 + 0.2,0.3) / / true copy the code
The user enters decimal numbers and the computer saves binary numbers. So there will be some deviation in the calculation results, so we should not directly compare the non-integers, but take the upper limit and take the error into account. Such an upper limit is called machine epsilon, and the standard epsilon value for double precision is 2 ^-53 (Math.pow (2,-53)).
Summary:
The code in this article may not be the optimal code, if you have better code, you are welcome to comment.
Reference:
Www.jianshu.com/p/c8b86b09d...
Www.cnblogs.com/wxydigua/p/...
Blog.csdn.net/u014607184/...
Rockjins.js.org/2017/02/15/...
Some tips to make JS more elegant / readable
For engineers, code is an important output that is written once, modified many times, and read more times, and readability is very important, so the importance of highly readable code is self-evident.
1. Replace switch / if with objects
Common content: let a = 'VIP' scene 1if (a =' VIP') {return 1} else if (a = 'SVIP') {return 2} scene 2switch (a) {case' VIP' return 1 break case 'SVIP' return 2 break} scene 3let obj = {VIP: 1, SVIP: 2} copy code
This only provides a way, the specific use of the scene or you have to judge. One of the scenarios I use more often is the Chinese meaning of state mapping. For example, the payment status usually obtains a value of 1,2magin3, 4, but the list requires that the corresponding Chinese status is not paid | in payment | refunded, etc.
2. Ingenious use of | | and & &
/ / scenario 1function b (a) {if (a) {return a} else {return'}} / / scenario 2function b (a) {return a | |''} copy code
The above is the use of |, also known as short-circuit handling. It is common in if conditions, but it can also be used directly in statements. When the first parameter is true, it takes the value of the first parameter, and when the first parameter is not true, it takes the value of the second parameter. & & is exactly the opposite of |. The first parameter is true, which takes the value of the second parameter.
The above is all the content of this article "what are the JS development skills?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.