Simultaneously published on wechat public account: Front-end Weizhi


In our last post on “Chrome DevTools Tips you may not know”, I got a lot of feedback from developers who did not know these tips. Today, we’re going to talk about some tricks in EcmaScript 5/6+, and feel free to discuss more in the comments section.


JSON.stringify

JSON objects are often used. For example, when we want to make a deep copy of an object, we can use json.stringify and json.parse to copy the exact same object without any reference to the original object. When using localStorage, it will also be used, because localStorage can only store the content in string format, so, before we save, we convert the value into JSON string, take out the time to use, and then into an object or array.

For the json.stringify method, it can help us convert an object or array into a JSON string. We usually only use its first parameter, but it has two other parameters that make it do some really nice things.

Let’s start with the syntax:

JSON.stringify(value[, replacer [, space]])

Parameters:

  • Value: The value of the variable to be serialized
  • Replacer: replacer. It could be a function or an array, or if it’s a function, thenvalueEach attribute is processed by this function, which returns the value that was finally serialized. If it is an array, the elements of the array are required to be strings, and these elements are treated asvalueThe key (keyThe result of the serialization is that only each element of the array iskeyThe value of the.
  • Space: Specifies the code indentation of the output value, which can be a number or a string, for formatting purposes. The number of Spaces to indent each line of code, if it is a number (up to 10). If it is a string, the string (up to the first ten characters) is displayed before each line of code.

At this point, you should know. We can use json.stringify for serialization filtering, which means we can customize json.stringify parsing logic.

Filter and serialize objects using functions:

Function replacer(key, value) {if (typeof value === "string") {return undefined; } return value; } var foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7 }; var jsonString = JSON.stringify(foo, replacer); // {"week":45,"month":7}Copy the code

Filter and serialize objects using arrays:

Const user = {name: 'zollero', Nick: 'z', skills: ['JavaScript', 'CSS', 'HTML5']}; // Const user = {name: 'zollero', Nick: 'z', skills: ['JavaScript', 'CSS', 'HTML5']} JSON.stringify(user, ['name', 'skills'], 2); // "{ // "name": "zollero", // "skills": [ // "JavaScript", // "CSS", // "HTML5" // ] // }"Copy the code

Another interesting thing is the toJSON property of the object.

If an object has a toJSON attribute, when it is serialized, the object is not serialized, but the return value of its toJSON method is serialized.

See the following example:

var obj = { foo: 'foo', toJSON: function () { return 'bar'; }}; JSON.stringify(obj); // '"bar"' JSON.stringify({x: obj}); // '{"x":"bar"}'Copy the code

Set to achieve array deduplication

In ES6, a new data structure type was introduced: Set. The structure of Set and Array is very similar, and Set and Array can be converted to each other.

Array to heavy, is also a common front end test, there are many methods, here is not repeated. Let’s look at using Set and… The (extended operator) can easily perform array de-duplication.

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]
Copy the code

Avoid naming conflicts with block-level scopes

During development, you often encounter naming conflicts, where different values need to be defined for different scenarios to assign to the same variable. Here’s a way to solve this problem using block-level scopes in ES6.

For example, when using a Switch case, we can do this:

switch (record.type) { case 'added': { const li = document.createElement('li'); li.textContent = record.name; li.id = record.id; fragment.appendChild(li); break; } case 'modified': { const li = document.getElementById(record.id); li.textContent = record.name; break; }}Copy the code

Function parameter value verification

As we know, in ES6, we have added the feature of default values for parameters of functions. We can set some default values for parameters, which makes the code more concise and maintainable.

In fact, we can use this feature to do the function parameter value verification.

First, function arguments can be values of any type or functions, such as this one:

function fix(a = getA()) {
  console.log('a', a)
}

function getA() {
  console.log('get a')
  return 2
}

fix(1);
// a 1

fix();
// get a
// a 2
Copy the code

As you can see, if a is passed when calling fix, the function getA will not be executed, and only if a is not passed will the function getA be executed.

In this case, we can use this feature to add a mandatory check to parameter A as follows:

Function require(a = require()) {console.log('a', a)} function require() {throw new Error(' missing argument a')} fix(1); // a 1 fix(); // Uncaught Error: Parameter A is missingCopy the code

Filter object properties with destructively assigned values

Earlier we showed you how to use json.stringify to filter the attributes of an object. Here, we present another way to filter attributes using the deconstruction assignment and extension operator features in ES6.

For example, here’s an example:

Const {inner, outer... const {inner, outer... restProps } = { inner: 'This is inner', outer: 'This is outer', v1: '1', v2: '2', v4: '3' }; console.log(restProps); // {v1: "1", v2: "2", v4: "3"}Copy the code

Gets the properties of a nested object with a destruct assignment

Destruct assignment is a powerful feature that allows us to easily get the object we want from a set of deeply nested attributes. Take this code for example:

Const car = {model: 'BMW 2018', engine: {v6: true, Turbo: true, vin: 12345}}; Const modalAndVIN = ({model, engine: {vin}}) => {console.log(' model: ${model}, vin: ${vin}`); } modalAndVIN(car); // "model: bmw 2018, vin: 12345"Copy the code

Merge objects

The new extension operator in ES6 can be used to deconstruct arrays as well as objects by expanding all properties in an object.

With this feature, we can do some object merge operations like the following:

Const obj1 = {a: 1, b: 2, c: 3}; const obj1 = {a: 1, b: 2, c: 3}; const obj2 = { c: 5, d: 9 }; const merged = { ... obj1, ... obj2 }; console.log(merged); // {a: 1, b: 2, c: 5, d: 9} const obj3 = { a: 1, b: 2 }; const obj4 = { c: 3, d: { e: 4, ... obj3 } }; console.log(obj4); // {c: 3, d: {a: 1, b: 2, e: 4} }Copy the code

Use === instead of ==

In JavaScript, === is very different from ==, which escapes variables on both sides and then compares the escaped values, whereas === is a strict comparison, requiring variables on both sides not only to have the same value, but also to have the same type.

JavaScript is often teased as a magic language because of its escape nature, and using == can introduce some deeply buried bugs. To avoid bugs, use === :

[10] ==  10      // true
[10] === 10      // false

'10' ==  10      // true
'10' === 10      // false

 []  ==  0       // true
 []  === 0       // false

 ''  ==  false   // true
 ''  === false   // false
Copy the code

Of course, there are problems with using ===, such as:

NaN === NaN  // false
Copy the code

ES6 provides a new method: object.is (), which has some characteristics of ===, but is better and more accurate, and can be realized better in some special scenarios:

Object.is(0 , ' ');         //false
Object.is(null, undefined); //false
Object.is([1], true);       //false
Object.is(NaN, NaN);        //true
Copy the code

Here is a comparison of ==, === and object. is:



Reference:

developer.mozilla.org/

www.jstips.co/