By Euel Duran

Source: Dev

Translator: Front-end wisdom

The more you know, the more you don’t know

Like it and see. Make it a habit


GitHub: github.com/qq449245884… Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.

JS is a rapidly developing language, and because of this, there are some new features and functions that we don’t know in time. In this article, we’ll focus on some lesser-known features and some common techniques.

Gets the query string parameter

URLSearchParams is an interface that defines some useful methods for handling URL query strings. It has been around for several years, but it is somewhat surprising that it is not popular among developers. Let’s see how to use it

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
Copy the code

Use the Set object to create a unique list of elements

Creating unique lists with JS is a common task and is usually done through filters or for loops, but there is another way to do this using a Set object.

const list = [1, 2, 3, 5, 2, 5, 7];
const uniqueList = [...new Set(list)];
Copy the code

An array of raw values is passed to a Set object, which creates a Set of unique values and then uses expansion operator syntax and array literals to convert those values back into the array.

Converts the original list of values to another type

Sometimes the data being processed in the background or in the DOM is not of the type we need. I’ve seen this happen when working with properties of datasets. Assume the following list:

const naiveList = ['1500', '1350', '4580'];
Copy the code

If you want to calculate the sum of all the elements in an array, in JS, you add strings and you concatenate two strings like ‘1’ + ‘2’ and they concatenate ’12’, normally, to solve this problem, we would use the parseInt function, but there’s another way; We can convert the elements of the array to the desired primitive type

const castedList = naiveList.map(Number);
console.log(castedList) // [1500, 1350, 4580]
Copy the code

CastedList now contains values with the correct Number type.

Flat nested arrays

With the rise of concepts such as single-page application architectures (such as Redux) and front-end data normalization, this trend toward “data normalization” sometimes means that all element ids need to be at the same level.

Suppose we have the following list and we want to flatten it:

const nestedList = [133, 235, 515, [513, 15]];
const flattenList = nestedList.flat();
console.log(flattenList) //  [133, 235, 515, 513, 15]
Copy the code

Just like that, our array of ids is flattened.

Use object. freeze to avoid objects being changed

With the rise of functional X programming, immutable data is becoming more important, and we can use object. freeze to prevent objects from being changed.

Const immutableObject = {name: 'front end ', url: 'https:// 66.com'}; Object.freeze(immutableObject); ImmutableObject. Wechat = 'qq449245884' immutableObject. Name = 'vdaz' console.log(immutableObject) // {name: "小智", url: "Https://, 66. com little wisdom"}Copy the code

Create a controlled Object using object.seal

The object.seal () method seals an Object, preventing the addition of new properties and marking all existing properties as unconfigurable. The value of the current property can be changed as long as it is writable, object.freeze does nothing, and Object.seal() can change the value of the property.

Const controlledObject = {name: 'front end'}; Object.seal(controlledObject); Controlledobject. name = 'wangdaye '; Controlledobject. hero = 'hero '; Console. log(controlledObject) // {name: wang Daye}Copy the code

Ensuring array values

With grid, you need to recreate the original data, and the column lengths of each row may not match. To ensure that the lengths of the mismatched rows are equal, use the array.fill method.

let array = Array(5).fill('');
console.log(array); // outputs (5) ["", "", "", "", ""]
Copy the code

Array map method (without array.map)

Another way to implement Array maps is not array.map.

Array.from can also take a second argument, similar to the map method of arrays, that is used to process each element and place the value in the returned Array. As follows:

const cities = [
    { name: 'Paris', visited: 'no' },
    { name: 'Lyon', visited: 'no' },
    { name: 'Marseille', visited: 'yes' },
    { name: 'Rome', visited: 'yes' },
    { name: 'Milan', visited: 'no' },
    { name: 'Palermo', visited: 'yes' },
    { name: 'Genoa', visited: 'yes' },
    { name: 'Berlin', visited: 'no' },
    { name: 'Hamburg', visited: 'yes' },
    { name: 'New York', visited: 'yes' }
];

const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
// outputs ["Paris", "Lyon", "Marseille", 
// "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]
Copy the code

Conditional object properties

Instead of creating two different objects based on a condition, you can use the expansion notation to handle it.

nst getUser = (emailIncluded) => { return { name: 'John', surname: 'Doe', ... emailIncluded && { email : '[email protected]' } } } const user = getUser(true); console.log(user); // outputs { name: "John", surname: "Doe", email: "[email protected]" } const userWithoutEmail = getUser(false); console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }Copy the code

Dynamic property name

In the early days, if the attribute name needed to be dynamic, we first had to declare an object and then assign an attribute. Those days are over, and with ES6 features, we can do just that.

const dynamic = 'email';
let user = {
    name: 'John',
    [dynamic]: '[email protected]'
}
console.log(user); // outputs { name: "John", email: "[email protected]" }
Copy the code

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: dev. To/duranenmanu…

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.