Just like any other programming language, JavaScript has many tricks to accomplish both simple and difficult tasks. Some of these techniques are already well known, while others will be refreshing. Let’s take a look at seven JavaScript tricks you can start using today.
Array to heavy
This is easy to implement using ES6’s new data structures.
Var j = [...new Set([1, 2, 3, 3])]Copy the code
For details about how to use Set, see ES6 Getting Started
Arrays and Booleans
When an array needs to quickly filter out false values (0,undefined,false, etc.), it is usually written like this:
myArray
.map(item => {
// ...
})
// Get rid of bad values
.filter(item => item);
Copy the code
You can do it more succinct using Boolean
myArray
.map(item => {
// ...
})
// Get rid of bad values
.filter(Boolean);
Copy the code
Such as:
The console. The log ([1, 0, null]. Filter (Boolean)); // Output: [1]Copy the code
Create an empty object
You would normally use {} to create an empty object, but the object would actually have __proto__ and hasOwnProperty methods and other methods.
var o = {}
Copy the code
For example, there are some object methods:
But to create a pure “dictionary” object, you can do this:
let dict = Object.create(null);
// dict.__proto__ === "undefined"// The object does not have any properties or methodsCopy the code
Merge objects
This one uses the expansion operator (…) Can be simply implemented:
const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue'}; const summary = {... person, ... tools, ... attributes}; /* Object {"computer": "Mac"."editor": "Atom"."eyes": "Blue"."gender": "Male"."hair": "Brown"."handsomeness": "Extreme"."name": "David Walsh",
}
*/
Copy the code
Function parameter verification is mandatory
Setting default parameters for functions is a nice addition to JS, but the following trick requires that the parameter values passed in be checked.
const isRequired = () => { throw new Error('param is required'); }; // When the name argument is not provided, the isRequired function is executed. Since this function throws an error, the developer knows during the call that the parameter needs to be passed. When passed, the isRequired function does not execute and the program runs normally. const hello = (name = isRequired()) => { console.log(`hello${name}`)}; // If no value is passed, throw hello(); // Throw an exception hello(undefined); // Check through hello(null); hello('David');
Copy the code
Function default arguments allow default parameters to be used when no value is passed or when undefined is passed. If the default value is an expression, then the expression is evaluated lazily, meaning that it is evaluated only when used. View the default parameters
Deconstruction alias
const obj = { x: 1 }; Const {x} = obj; const {x} = obj; Const {x: otherName} = obj;Copy the code
Gets the query string parameters
Use the URLSearchParamsAPI to easily get the values of each item in the query string:
// Assuming "? post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); / / /"edit"]
console.log(urlParams.toString()); // "? post=1234&action=edit"
console.log(urlParams.append('active'.'1')); // "? post=1234&action=edit&active=1"
Copy the code
(after)
reference
- The original link
- The default parameters