In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to use JS development skills", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn "how to use JS development skills"!
String Skill
Contrast time
The single digit form of time needs to be added 0.
Const time1 = "2019-02-14 21:00:00"; const time2 = "2019-05-01 09:00:00"; const overtime = time1 > time2; / / overtime = > false
Format money
Const ThousandNum = num = > num.toString (). Replace (/\ B (? = (\ d {3}) + (?!\ d)) / g, ","); const money = ThousandNum (20190214); / / money = > "20190214"
Generate random ID
Const RandomId = len = > Math.random (). ToString (36) .substr (3, len); const id = RandomId (10); / / id = > "jg7zpgiqva"
Generate random HEX color values
Const RandomColor = () = > "#" + Math.floor (Math.random () * 0xffffff) .toString (16) .padEnd (6, "0"); const color = RandomColor (); / / color = > "# f03665"
Generate a star score
Const StartScore = rate = > "★☆" .slice (5-rate, 10-rate); const start = StartScore (3); / / start = > "★★★"
Manipulate URL query parameters
Const params = new URLSearchParams (location.search.replace (/\? / ig, ")); / / location.search ="? name=young&sex=male "params.has (" young "); / / true params.get (" sex "); / /" male "
Number Skill
Rounding
Instead of positive Math.floor (), instead of negative Math.ceil ()
Const num1 = ~ 1.69; const num2 = 1.69 | 0; const num3 = 1.69 > > 0; / / num1 num2 num3 = > 11
Make up zero
Const FillZero = (num, len) = > num.toString (). PadStart (len, "0"); const num = FillZero (169,5); / / num = > "00169"
Rotation value
Valid only for null, "", false, numeric strings
Const num1 = + null; const num2 = + ""; const num3 = + false; const num4 = + "169"; / / num1 num2 num3 num4 = > 0.00169
Time stamp
Const timestamp = + new Date ("2019-02-14"); / / timestamp = > 1550102400000
Exact decimal
Const RoundNum = (num, decimal) = > Math.round (num * 10 * * decimal) / 10 * * decimal; const num = RoundNum (1.69,1); / / num = > 1.7
Judge parity
Const OddEven = num = >! (num & 1)? "odd": "even"; const num = OddEven (2); / / num = > "even"
Take the minimum and maximum
Const arr = [0,1,2]; const min = Math.min (.arr); const max = Math.max (.arr); / / min max = > 0 2
Generate range random number
Const RandomNum = (min, max) = > Math.floor (Math.random () * (max-min + 1)) + min; const num = RandomNum (1,10)
Boolean Skill
Short circuit operator
Const a = d & & 1; / / satisfying condition assignment: take false operation, judge from left to right, return false value if encountered, and then no longer execute, otherwise return the last true value const b = d | | 1; / / default assignment: take true operation, judge from left to right, return true value when encountered true value, then no longer execute, otherwise return the last false value const c =! d / / false assignment: false is returned if a single expression is converted to true, otherwise true is returned
Determine the data type
Identifiable types: undefined, null, string, number, boolean, array, object, symbol, date, regexp, function, asyncfunction, arguments, set, map, weakset, weakmap
Function DataType (tgt, type) {const dataType = Object.prototype.toString.call (tgt). Replace (/\ [object / g, "). Replace (/\] / g,") .toLowerCase (); return type? DataType = type: dataType;} DataType ("young"); / / "string" DataType (20190214); / / "number" DataType (true); / / "boolean" DataType ([], "array"); / / true DataType ({}, "array"); / / false
Whether it is an empty array
Const arr = []; const flag = Array.isArray (arr) & &! arr.length; / / flag = > true
Whether it is an empty object
Const obj = {}; const flag = DataType (obj, "object") & &! Object.keys (obj) .length; / / flag = > true
Execute when conditions are met
Const flagA = true; / / conditional A const flagB = false; / / conditional B (flagA | | flagB) & & Func (); / / execute when An or B is satisfied (flagA | |! flagB) & & Func (); / / execute flagA & & flagB & & Func () when An is satisfied or B is not satisfied; / / execute flagA & & flagB & Func () when both An and B are satisfied; / / execute when An is satisfied and B is not satisfied
Execute when the value is not false
Const flag = false; / / undefined, null, "", 0, false, NaN! flag & & Func ()
Execute when the array is not empty
Const arr = [0,1,2]; arr.length & & Func ()
Executes when the object is not empty
Const obj = {a: 0, b: 1, c: 2}; Object.keys (obj). Length & & Func ()
Function exit instead of conditional branch exit
If (flag) {Func (); return false;} / / replace it with if (flag) {return Func ();}
Switch/case usage range
Const age = 26; switch (true) {case isNaN (age): console.log ("not a number"); break; case (age)
< 18): console.log("under age"); break; case (age >= 18): console.log ("adult"); break; default: console.log ("please set your age"); break;}
Array Skill
Clone array
Const _ arr = [0,1,2]; const arr = [... _ arr]; / / arr = > [0,1,2]
Merge array
Const arr1 = [0,1,2]; const arr2 = [3,4,5]; const arr = [... arr1,... arr2]; / / arr = > [0,1,2,3,4,5]
Deduplicated array
Const arr = [. New Set ([0,1,1, null, null])]; / / arr = > [0,1, null]
Confusing array
Const arr = [0,1,2,3,4,5] .slice () .sort (() = > Math.random ()-.5); / / arr = > [3,4,0,5,1,2]
Empty the array
Const arr = [0,1,2]; arr.length = 0; / / arr = > []
Truncated array
Const arr = [0,1,2]; arr.length = 2; / / arr = > [0,1]
Exchange assignment
Let a = 0; let b = 1; [a, b] = [b, a]; / / a b = > 10
Filter null value
Null values: undefined, null, "", 0, false, NaN
Const arr = [undefined, null, "", 0, false, NaN, 1,2] .filter (Boolean); / / arr = > [1,2]
Asynchronous accumulation
Async function Func (deps) {return deps.reduce (async (t, v) = > {const dep = await t; const version = await Todo (v); dep [v] = version; return dep;}, Promise.resolve ({}));} const result = await Func (); / / need to be surrounded by async
Array header insert member
Let arr = [1,2]; / / choose one of the following methods: arr.unshift (0); arr = [0] .concat (arr); arr = [0,... arr]; / / arr = > [0,1,2]
Insert member at the end of the array
Let arr = [0,1]; / / choose one of the following methods: arr.push (2); arr.concat (2); arr [arr.length] = 2; arr = [... arr, 2]; / / arr = > [0,1,2]
Count the number of members of the array
Const arr = [0,1,1,2,2,2]; const count = arr.reduce ((t, c) = > {t [c] = t [c]? + t [c]: 1; return t;}, {}); / / count = > {0: 1, 1: 2, 2: 3}
Member nesting of deconstructed array
Const arr = [0,1, [2,3, [4,5]; const [a, b, [c, d, [e, f] = arr; / / a b c d e f = > 0 123 45
Deconstructing array member alias
Const arr = [0,1,2]; const {0: a, 1: B, 2: C} = arr; / / a b c = > 0 12
Destructing array member default values
Const arr = [0,1,2]; const [a, b, c = 3, d = 4] = arr; / / a b c d = > 0 124
Get random array members
Const arr = [0,1,2,3,4,5]; const randomItem = arr [Math.floor (Math.random () * arr.length)]; / / randomItem = > 1
Create an array of specified lengths
Const arr = [. New Array (3). Keys ()]; / / arr = > [0,1,2]
Creates an array of specified length and equal values
Const arr = new Array (3) .fill (0); / / arr = > [0,0,0]
Reduce replaces map and filter
Const _ arr = [0,1,2]; / map const arr = _ arr.map (v = > v * 2); const arr = _ arr.reduce ((t, c) = > {t.push (c * 2); return t;}, []); / / arr = > [0,2,4] / / filter const arr = _ arr.filter (v = > v > 0) Const arr = _ arr.reduce ((t, c) = > {c > 0 & & t.push (c); return t;}, []); / / arr = > [1,2] / / map and filter const arr = _ arr.map (v = > v * 2) .filter (v = > v > 2); const arr = _ arr.reduce ((t, c) = > {cc = c * 2; c > 2 & t.push (c); return t) }, []); / / arr = > [4]
Object Skill
Clone object
Const _ obj = {a: 0, b: 1, c: 2}; / / choose one of the following methods: const obj = {... _ obj}; const obj = JSON.parse (JSON.stringify (_ obj)); / / obj = > {a: 0, b: 1, c: 2}
Merge object
Const obj1 = {a: 0, b: 1, c: 2}; const obj2 = {c: 3, d: 4, e: 5}; const obj = {... obj1,... obj2}; / / obj = > {a: 0, b: 1, c: 3, d: 4, e: 5}
Object literal quantity
You must use this method when getting environment variables, use it all the time, always use it
Const env = "prod"; const link = {dev: "Development Address", test: "Testing Address", prod: "Production Address"} [env]; / / link = > "Production Address"
Object variable attribute
Const flag = false; const obj = {a: 0, b: 1, [flag? "c": "d"]: 2}; / / obj = > {a: 0, b: 1, d: 2}
Create a pure empty object
Const obj = Object.create (null); Object.prototype.a = 0; / / obj = > {}
Delete object useless attribute
Const obj = {a: 0, b: 1, c: 2}; / / just want to take b and c const {a,... rest} = obj; / / rest = > {b: 1, c: 2}
Deconstruct object property nesting
Const obj = {a: 0, b: 1, c: {d: 2, e: 3}}; const {c: {d, e}} = obj; / / d e = > 2 3
Deconstruct object property alias
Const obj = {a: 0, b: 1, c: 2}; const {a, b: d, c: e} = obj; / / a d e = > 0 12
Deconstruct object attribute defaults
Const obj = {a: 0, b: 1, c: 2}; const {a, b = 2, d = 3} = obj; / / a b d = > 0 13
Function Skill
Function self-execution
Const Func = function () {} (); / / commonly used (function () {}) (); / / commonly used (function () {} ()); / / commonly used [function () {} ()]; + function () {} ();-function () {} (); ~ function () {} ();! Function () {} (); new function () {}; new function () {} (); void function () {} (); typeof function () {} (); delete function () {} (); 1, function () {} (); 1 ^ function () {} (); 1 > function () {} ()
Implicit return value
Can only be used for single statement return value arrow function. If the return value is an object, it must be wrapped with ().
Const Func = function (name) {return "I Love" + name;}; / / replace with const Func = name = > "I Love" + name
One-time function
Suitable for running initialization code that only needs to be executed once
Function Func () {console.log ("x"); Func = function () {console.log ("y");}}
Lazy load function
The cost of resources can be greatly saved when there are more and more complex branches in the function.
Function Func () {if (a = b) {console.log ("x");} else {console.log ("y");}} / / replace with function Func () {if (a = b) {Func = function () {console.log ("x") }} else {Func = function () {console.log ("y");}} return Func ();}
Detect non-null parameters
Function IsRequired () {throw new Error ("param is required");} function Func (name = IsRequired ()) {console.log ("I Love" + name);} Func (); / / "param is required" Func ("You"); / / "I Love You"
String creation function
Const Func = new Function ("name", "console.log (\" I Love\ "+ name)")
Handle error messages gracefully
Try {Func ();} catch (e) {location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;}
Elegant handling of Async/Await parameters
Function AsyncTo (promise) {return promise.then (data = > [null, data]) .catch (err = > [err]);} const [err, res] = await AsyncTo (Func ())
Elegantly handle the return values of multiple functions
Function Func () {return Promise.all ([fetch ("/ user"), fetch ("/ comment"));} const [user, comment] = await Func (); / / need to be surrounded by async
DOM Skill
Show all DOM borders
When debugging page element boundaries, use the
[] .forEach.call ($$("*"), dom = > {dom.style.outline = "1px solid #" + (~ (Math.random ()) *) (target.style.fontSize = "80px"): (targettarget.style.fontSize = target.clientWidth / width * 100 + "px");}
Filter XSS
Function FilterXss (content) {let elem = document.createElement ("div"); elem.innerText = content; const result = Elm [XSS _ clean]; elem = null; return result;}
Access LocalStorage
Deserialization storage
Const love = JSON.parse (localStorage.getItem ("love")); localStorage.setItem ("love", JSON.stringify ("I Love You")); now that you have a better understanding of "how to use JS development skills", you might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.