Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the tips of JavaScript?

2025-01-18 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 tips of JavaScript", the content is simple and clear, and I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "what tips does JavaScript have?"

1. Delete the element at the end of the array

A simple way to clear or delete elements at the end of an array is to change the value of the length attribute of the array.

Const arr = [11, 22, 33, 44, 55, 66]; / / truncantingarr.length = 3 position console.log (arr); / / = > [11, 22, 33] / / clearingarr.length = 0 position console.log (arr); / / > [] console.log (arr [2]); / / = > undefined

two。 Use object deconstruction to simulate named parameters

If you need to pass a series of options as arguments to the function, you may prefer to use an object (Object) to define the Config.

DoSomething ({foo: 'Hello', bar:' Heymilk, baz: 42}); function doSomething (config) {const foo = config.foo! = = undefined? Config.foo: 'Hi'; const bar = config.bar! = = undefined? Config.bar: 'Yoshiyama; const baz = config.baz! = = undefined? Config.baz: 13; / /.}

This is an old but effective method that simulates named parameters in JavaScript. However, the way to deal with config in doSomething is a bit cumbersome. In ES2015, you can use object deconstruction directly.

Function doSomething ({foo = 'Hi', bar =' Yoshiyama, baz = 13}) {/ /...}

If you want this parameter to be optional, it's also simple.

Function doSomething ({foo = 'Hi', bar =' Yoshiyama, baz = 13} = {}) {/ /...}

3. Using object deconstruction to work with arrays

You can use object deconstruction syntax to get the elements of an array:

Const csvFileLine = '1997 Doe,US,john@doe.com,New York';const {2: country, 4: state} = csvFileLine.split (',')

4. Use range values in switch statements

You can use the following techniques to write switch statements that satisfy range values:

Function getWaterState (tempInCelsius) {let state; switch (true) {case (tempInCelsius 0 & & tempInCelsius)

< 100): state = 'Liquid'; break; default: state = 'Gas'; } return state;} 5. await多个async函数 在使用async/await的时候,可以使用Promise.all来await多个async函数。 await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()]) 6. 创建一个纯(pure)对象 你可以创建一个100%的纯对象,他不从Object中继承任何属性或则方法(比如,constructor,toString()等等)。 const pureObject = Object.create(null);console.log(pureObject); //=>

{} console.log (pureObject.constructor); / / = > undefinedconsole.log (pureObject.toString); / / = > undefinedconsole.log (pureObject.hasOwnProperty); / / = > undefined

7. Format JSON code

JSON.stringify can not only characterize an object, but also format the output JSON object.

Const obj = {foo: {bar: [11, 22, 33, 44], baz: {bing: true, boom: 'Hello'}; / / The third parameter is the number of spaces used to / / beautify the JSON output.JSON.stringify (obj, null, 4) / / > "{/ / = >" foo ": {/ / = >" bar ": [/ / = > 11 Hello / = > 22 pinch / = > 3 > 44 pinch / >], / / = >" baz ": {/ / = >" bing ": true,// = >" boom ":" Hello "/ / = >}"

8. Remove repeating elements from an array

In ES2015, you have the syntax for collections. Duplicate elements can be easily removed by using collection syntax and Spread operations:

Const removeDuplicateItems = arr = > [... new Set (arr)]; removeDuplicateItems ([42, 'foo', 42,' foo', true, true]); / / = > [42, "foo", true]

9. Tiled multidimensional array

Using the Spread operation, you can easily tile nested multidimensional arrays:

Const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [] .concat (.arr); / / = > [11, 22, 33, 44, 55, 66]

Unfortunately, the above method only applies to two-dimensional arrays. However, through recursion, we can tile nested arrays of any dimension.

Unction flattenArray (arr) {const flattened = [] .concat (.. arr); return flattened.some (item = > Array.isArray (item))? FlattenArray (flattened): flattened;} const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]; const flatArr = flattenArray (arr); / / = > [11, 22, 33, 44, 55, 66, 77, 88, 99]

That's all! I hope these tips can help you write more beautiful JS code! If it's not enough, then you might as well use Fundebug as your assistant!

Selected comments

Ethan B Martin: this switch is cleverly written, but it is not recommended. Please do not encourage developers to write JS code in this way. We once had an engineer who wrote this, and then when the code review, it caused a lot of reading hardship. Fortunately, we refactored it into code that was easier to read in time. Compare the difference between using swtich and if:

Function getWaterState1 (tempInCelsius) {let state; switch (true) {case (tempInCelsius)

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report