Array weight removal
var arr = [1, 2, 3, 3, 4]; console.log(...new Set(arr)) >> [1, 2, 3, 4]
Arrays and Booleans
Sometimes we need to filter the value of false in the array. For example (0, undefined, null, false), you may not know such a trick.
var myArray = [1, 0 , undefined, null, false]; myArray.filter(Boolean); > > [1] //Is it very simple? Just pass in a Boolean function.
Create an empty object
Sometimes we need to create a pure object without any prototype chain and so on. Generally, the most direct way to create an empty object is through literal {}, but there are still proto attributes in this object to point to Object.prototype and so on.
let dict = Object.create(null); dict.__proto__ === "undefined"
Merge object
There is always a need to merge multiple objects in JavaScript. For example, when passing parameters, you need to merge form parameters and paging parameters and then pass them to the backend.
const page = { current: 1, pageSize: 10 } const form = { name: "", sex: "" } const params = {...form, ...page}; /* { name: "", sex: "", current: 1, pageSize: 10 } *
Using the extended operators provided by ES6 makes object merging very easy.
Function arguments must
In ES6, you can specify default values for parameters, which really brings a lot of convenience. If you need to detect that some parameters are required to be passed, you can do so.
const isRequired = () => { throw new Error('param is required'); }; const hello = (name = isRequired()) => { console.log(`hello ${name}`) }; // An error will be thrown here because the name must be hello(); // This will also throw an error hello(undefined); // normal hello(null); hello('David');
Use aliases when deconstructing assignments
Deconstruction assignment is a very popular JavaScript function, but sometimes we prefer to refer to these properties with other names, so we can use aliases to do this:
const obj = { x: 1 }; // Grabs obj.x as { x } const { x } = obj; // Grabs obj.x as { otherName } const { x: otherName } = obj;
Get query parameters
Over the years, we've written rough regular expressions to get query string values, but those days are gone; now we can get query parameters through the URLSearchParams API
Without using URLSearchParams, we can obtain query parameters in a regular way, as follows:
function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); return r ? r[2] : null; }
After using URLSearchParams:
// Suppose the query parameter in the address bar is "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"