introduction
The reason for writing this article is that I worked in the front-end team of the company last weekcode 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 projectsjs
It’s not very skillful and lacks some skills.
Therefore, this paper sorts out some common problems in the developmentjs
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 traversalindexOf
It’s the same way.
double-deckfor
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;
}
utilizeindexOf
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 useArray.from
Andset
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 {
feeling = 'bad'
}
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-calledSingle line
The idea is that code tends toSimplicity
。
Convert to numeric type(Convert to Number
)🔢
This is very common, we use more may beparseInt()
、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 withtoString()
、String()
realization:
let a = 123;
a.toString(); // '123'
But it can also be passedvalue + ""
In this way:
let a = 123;
a + ""; // '123'
Performance tracking
If you want to test a paragraphjs
The code takes time to execute, so you can try itperformance
:
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 beObject.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, throughSpread 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 userecursion
orreduce
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));
howeveres6
A new method is providedflat(depth)
, parametersdepth
Represents the depth of the expanded nested array. The default value is1
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 moreMath.pow()
For example2^10
:
console.log(Math.pow(2, 10));
stayES7
The exponential operator is introduced in**
,**
With andMath.pow()
The same result.
console.log (2 * * 10); // output 1024
Floating point to integer(Float to Integer
)🦊
We usually convert floating-point numbers to integersMath.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 throughslice
Operation
let arr = [0, 1, 2, 3, 4, 5];
const last = arr.slice(-1)[0];
console.log(last);
Output: 5;
Beautify your lifeJSON
💄
We often use it in daily developmentJSON.stringify
But you may not know exactly what parameters he has.
He has three parameters:
json
: required, can be array orObject
replacer
: optional value, which can be array or methodspace
: what is used to separate
And we can just specify the third parameterspace
To beautify our lifeJSON
:
Object.create(null)
🐶
stay
Vue
andVuex
Source code, the author usedObject.create(null)
To initialize a new object. Why not use a simpler one{}
What about it?
Let’s take a lookObject.create()
Definition of
Object.create(proto, [propertiesObject]);
proto
: the prototype object of the newly created objectpropertiesObject
: 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 themObject.create(null)
and{}
Different ways to create objects:
As you can see from the above figure, the{}
Created object inheritsObject
Their own methods, such ashasOwnProperty
、toString
It can be used directly on new objects.
And useObject.create(null)
Created objects, in addition to their own propertiesa
Besides, there are no attributes on the prototype chain.
That is, we can go through theObject.create(null)
This way to create apure
We can define our own objectshasOwnProperty
、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];
useArray
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 passswitch case
orincludes
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, theObject.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 itObject.freeze()
Freeze them, that’s itVue
You don’t do that to these objectssetter
orgetter
Can greatly improve the performance.
❤ Three combos of love
1. If you think this article is not bad, let’s give it a tryShare, like, watchThird, let more people see ~
2. pay attention to the official account.Front end forest, regular push fresh and dry goods for you.
3. In special stage, wear masks and do well in personal protection.