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 ten super-practical skills that JavaScript developers have overlooked?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what are the top ten super practical skills that JavaScript developers have ignored. The quality of the article content is high, so Xiaobian shares it with you as a reference. I hope that after reading this article, you will have a certain understanding of relevant knowledge.

As we all know, JavaScript updates very fast, always gives people a fresh feeling, there are always things that we can explore, the new ES2020 has a lot of particularly powerful features that people can't wait to try.

There are many ways to write code, and there are always ways to write code that is more concise and clear, which requires some tips.

method parameter verification

JavaScript can set default values for parameters, which provides a tip for validating method parameters:

const isRequired = () => { thrownew Error('param is required'); }; const print = (num =isRequired()) => { console.log(`printing ${num}`) }; print(2);//printing 2 print()// error print(null)//printing null

Format JSON encoding

You're certainly familiar with JSON.stringify, but do you format the output with stringify? This operation is actually very simple. Stringify requires three parameters, value , displacer and space. The latter two are optional parameters, so we haven't used it before. If you want to indent JSON, you must set the space parameter.

console.log(JSON.stringify({name:"John",Age:23},null,'\t'));>>> { "name": "John", "Age": 23 }

Get unique values from an array

Getting unique values from an array requires filtering out duplicates, but with the new set native object it becomes much easier.

let uniqueArray = [... newSet([1, 2, 3, 3,3,"school","school",'ball',false,false,true,true])]; >>> [1, 2, 3,"school", "ball", false, true]

Filter Numeric Array

JavaScript arrays come with built-in filtering methods. By default, this method converts array elements to strings and lexicographically sorts them. There may be problems when sorting arrays of numbers, but here's a simple solution:

[0,10,4,9,123,54,1].sort((a,b)=> a-b);>>> [0, 1, 4, 9, 10, 54, 123]

This function filters by comparing two elements in a numeric array to get the correct output.

Remove false values from arrays

Sometimes we may need to delete false values from an array, i.e. values that are equivalent to FALSE in JavaScript, which has six false values, including:

HarmonyOS Technology Community

undefined

null

NaN

0

"" (empty string)

false

An easy way to filter out spurious values is to use the following function:

myArray .filter(Boolean);

If you want to make some modifications to an array and then filter the new array, try the following. Remember, the original myArray remains unchanged.

myArray .map(item => { // Do your changes and return thenew item }) .filter(Boolean);

Merge multiple objects

When you want to merge two or more classes, the following method is very useful:

const user = { name: 'John Ludwig', gender: 'Male' };const college = { primary: 'Mani Primary School', secondary: 'Lass Secondary School' };const skills = { programming: 'Extreme', swimming: 'Average', sleeping: 'Pro' };const summary = {... user, ... college,... skills};

Wait until all the promises are complete.

Sometimes you need to wait for some promise objects to complete before proceeding to the next step, we can use Promise.all to complete synchronously. Note that all Promises can run simultaneously on a single-core CPU and in parallel on a multicore CPU. Its main task is to wait for all promise objects passed to it to be resolved.

const PromiseArray = [ Promise.resolve(100), Promise.reject(null), Promise.resolve("Datarelease"), Promise.reject(new Error('Somethingwent wrong'))];Promise.all(PromiseArray) .then(data => console.log('allresolved! here are the resolve values:', data)) .catch(err => console.log('gotrejected! reason:', err))

Promise.all The important thing to note is that if one of the promises is rejected, an error warning is issued. This means that your code doesn't have to wait for all the promise objects to be resolved.

If you want a promise to run regardless of whether it is rejected, you can use Promise.allSettled, which will be used in the final version of ES2020:

const PromiseArray = [ Promise.resolve(100), Promise.reject(null), Promise.resolve("Datarelease"), Promise.reject(new Error('Somethingwent wrong'))];Promise.allSettled(PromiseArray).then(res =>{ console.log(res); }).catch(err => console.log(err));//[ //{status: "fulfilled", value: 100}, //{status: "rejected", reason: null}, //{status: "fulfilled", value: "Data release"}, //{status: "rejected", reason: Error: Something went wrong ...} //]

Promise.allSettled returns the results of all promises, although some promises are rejected.

Disable right-click

Although rare, there are times when you might want to prevent users from using the right mouse button on a web page, and this simple code does the trick:

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