# Do you know all these operations in JavaScript?

Time：2021-2-23

## introduction

The reason for writing this article is that I worked in the front-end team of the company last week`code review`After looking at the code of an intern brother, I feel that some students who have just entered the industry are not satisfied with some problems in real projects`js`It’s not very skillful and lacks some skills.

Therefore, this paper sorts out some common problems in the development`js`Skill, flexible use, will enhance your ability to solve problems, will also have a great change in your code simplicity.

## Array de duplication

Normally, we implement the array to go through double-layer traversal or double-layer traversal`indexOf`It’s the same way.

### double-deck`for`Cycle weight removal

``````function unique(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1);
j--;
}
}
}
return arr;
}``````

### utilize`indexOf`duplicate removal

``````function unique(arr) {
if (!Array.isArray(arr)) {
console.log("type error!");
return;
}
var array = [];
for (var i = 0; i < arr.length; i++) {
if (array.indexOf(arr[i]) === -1) {
array.push(arr[i]);
}
}
return array;
}``````

But there’s a simpler way: to use`Array.from`And`set`duplicate removal

``````function unique(arr) {
if (!Array.isArray(arr)) {
console.log("type error!");
return;
}
return Array.from(new Set(arr));
}``````

Is the implementation of this code very concise

## Array to object（`Array to Object`）🦑

Most students first think of this method to convert arrays into objects

``````var obj = {};
var arr = ["1","2","3"];
for (var key in arr) {
obj[key] = arr[key];
}
console.log(obj)

Output:
{0: 1, 1: 2, 2: 3}``````

But there is a relatively simple and fast way:

``````const arr = [1,2,3]
const obj = {...arr}
console.log(obj)

Output:
{0: 1, 1: 2, 2: 3}``````

One line of code can do things, why use traversal?

## Rational use of ternary expressions

In some scenarios, we need to assign different values to variables according to different conditions. We often use the following method:

``````const isGood = true;
let feeling;
if (isGood) {
feeling = 'good'
} else {
}
console.log(`I feel \${feeling}`)

Output:
I feel good``````

But why not use ternary expressions?

``````const isGood = true;
const feeling = isGood ? 'good' : 'bad'
console.log(`I feel \${feeling}`)

Output:
I feel good``````

This is the so-called`Single line`The idea is that code tends to`Simplicity`

## Convert to numeric type（`Convert to Number`）🔢

This is very common, we use more may be`parseInt()``Number()`This:

``````const age = "69";
const ageConvert = parseInt(age);
console.log(typeof ageConvert);

Output: number;``````

In fact, it can also be passed`+`To achieve the transformation:

``````const age = "69";
const ageConvert = +age;
console.log(typeof ageConvert);

Output: number;``````

## Convert to string type（`Convert to String`）🔡

Conversion to a string is usually done with`toString()``String()`realization:

``````let a = 123;

a.toString(); // '123'``````

But it can also be passed`value + ""`In this way:

``````let a = 123;

a + ""; // '123'``````

## Performance tracking

If you want to test a paragraph`js`The code takes time to execute, so you can try it`performance`

``````let start = performance.now();
let sum = 0;
for (let i = 0; i < 100000; i++) {
sum += 1;
}
let end = performance.now();
console.log(start);
console.log(end);``````

## Merge objects（`Combining Objects`）🌊

Two objects merge, we use more may be`Object.assign`The following is true:

``````const obj1 = { a: 1 }
const obj2 = { b: 2 }
console.log(Object.assign(obj1, obj2))

Output:
{ a: 1, b: 2 }``````

There’s a simpler way:

``````const obj1 = { a: 1 }
const obj2 = { b: 2 }
const combinObj = { ...obj1, ...obj2 }
console.log(combinObj)

Output:
{ a: 1, b: 2 }``````

That is, through`Spread operator`To achieve.

## Short circuit operation（`Short-circuit evaluation`) 🥅

We can go through it`&&`or`||`To simplify our code, for example:

``````if (isOnline) {
postMessage();
}
//Use&&
isOnline && postMessage();

//Use||
Let name = null | "forest";``````

## Array flattening（`Flattening an array`）🍓

For flattening arrays, we usually use`recursion`or`reduce`To achieve

### recursion

``````var arr = [1, [2, [3, 4]]];

function flatten(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}

console.log(flatten(arr));``````

### `reduce`

``````var arr = [1, [2, [3, 4]]];

function flatten(arr) {
return arr.reduce(function (prev, next) {
return prev.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
}

console.log(flatten(arr));``````

however`es6`A new method is provided`flat(depth)`, parameters`depth`Represents the depth of the expanded nested array. The default value is`1`

``````let arr = [1, [2, 3, [4, [5]]]];
arr.flat(3); // [1,2,3,4,5]``````

## Exponentiation

Usually, we realize the exponential operation, which should be used more`Math.pow()`For example`2^10`

``console.log(Math.pow(2, 10));``

stay`ES7`The exponential operator is introduced in`**``**`With and`Math.pow()`The same result.

``console.log (2 * * 10); // output 1024``

## Floating point to integer（`Float to Integer`）🦊

We usually convert floating-point numbers to integers`Math.floor()``Math.ceil()``Math.round()`. But there is a faster way:

``````console.log(~~6.95); // 6
console.log(6.95 >> 0); // 6
console.log(6.95 << 0); // 6
console.log(6.95 | 0); // 6
//The negative number cannot be rounded
console.log(6.95 >>> 0); // 6``````

That is to use`~`, `>>`, `<<`, `>>>`, `|`These bit operators are used to implement rounding

## Truncate array

If you need to change the array length to a fixed value, you can try this

``````let array = [0, 1, 2, 3, 4, 5];
array.length = 3;
console.log(array);

Output: [0, 1, 2];``````

## Gets the last item in the array

Usually, we use the following methods to get the last item of an array:

``````let arr = [0, 1, 2, 3, 4, 5];
const last = arr[arr.length - 1];
console.log(last);

Output: 5;``````

But we can also get through`slice`Operation

``````let arr = [0, 1, 2, 3, 4, 5];
const last = arr.slice(-1)[0];
console.log(last);

Output: 5;``````

## Beautify your life`JSON` 💄

We often use it in daily development`JSON.stringify`But you may not know exactly what parameters he has.

He has three parameters:

• `json`: required, can be array or`Object`
• `replacer`: optional value, which can be array or method
• `space`: what is used to separate

And we can just specify the third parameter`space`To beautify our life`JSON`

## `Object.create(null)` 🐶

stay`Vue`and`Vuex`Source code, the author used`Object.create(null)`To initialize a new object. Why not use a simpler one`{}`What about it?
Let’s take a look`Object.create()`Definition of

``Object.create(proto, [propertiesObject]);``
• `proto`: the prototype object of the newly created object
• `propertiesObject`: optional. An enumerable property to be added to a new object (the newly added property is its own property, not one on its prototype chain).

Let’s compare them`Object.create(null)`and`{}`Different ways to create objects:

As you can see from the above figure, the`{}`Created object inherits`Object`Their own methods, such as`hasOwnProperty``toString`It can be used directly on new objects.

And use`Object.create(null)`Created objects, in addition to their own properties`a`Besides, there are no attributes on the prototype chain.

That is, we can go through the`Object.create(null)`This way to create a`pure`We can define our own objects`hasOwnProperty``toString`There is no need to worry about covering the same name method on the prototype chain.

## Copy array

In daily development, array copy is a common scene. In fact, there are many techniques for copying arrays.

### `Array.slice`

``````const arr = [1, 2, 3, 4, 5];
const copyArr = arr.slice();``````

### Expansion operator

``````const arr = [1, 2, 3, 4, 5];
const copyArr = [...arr];``````

### use`Array`Constructors and expansion operators

``````const arr = [1, 2, 3, 4, 5];
const copyArr = new Array(...arr);``````

### `Array.concat`

``````const arr = [1, 2, 3, 4, 5];
const copyArr = arr.concat();``````

## Avoid multi condition juxtaposition

Sometimes in the development, we will encounter multiple conditions and execute the same statement, that is, multiple conditions`||`This:

``````if (status === "process" || status === "wait" || status === "fail") {
doSomething();
}``````

This kind of writing is not very meaningful and readable. Can pass`switch case`or`includes`This method can be transformed.

### `switch case`

``````switch (status) {
case "process":
case "wait":
case "fail":
doSomething();
}``````

### `includes`

``````const enum = ["process", "wait", "fail"];
if (enum.includes(status)) {
doSomething();
}``````

## `Object.freeze()` 🃏

stay`Vue`When data binding and response are introduced in the document of, the`Object.freeze()`Object of method cannot respond to update.
`Object.freeze()`Method is used to freeze an object and prohibit modifying its properties.

Because of this feature, it has many applicable scenarios in the actual project.

Like some pure display pages, there may be huge arrays or objects. If the data does not change, you can use it`Object.freeze()`Freeze them, that’s it`Vue`You don’t do that to these objects`setter`or`getter`Can greatly improve the performance.