Some tips to improve the elegance of JavaScript code "1"

Introduction

A summary of some common abbreviation techniques in JavaScript, let the code say goodbye to the shit mountain, start with me!



1. Optional chain to prevent crashes (?.)

Optional chaining operator?. Generates an error if an undefined property is accessed. This is where optional chaining comes in. When using the optional chaining operator when a property is undefined, undefined will be returned instead of an error. This prevents your code from crashing.

const person = {
    
    
  name: "张三",
   age: 30,
   address: {
    
    
     area: "beijing"
   },
 }
 // 一层一层判断
 console.log(person && person.address && person.address.province) // 输出:undefined
 // 使用可选链操作符
 console.log(person?.address?.province) // 输出:undefined

2. Correct usage posture of includes

There is an if judgment in the operator || code segment that is relatively long. At this time, you can use includes to simplify the code.

if(val === 0 ||  val === "" || val === false || val === null || val === undefined){
    
    
  // ...
}
// 使用includes简化
if([0, '', false, null, undefined].includes(val)){
    
    
  // ...
}

To check whether a field exists in an array, you can use the includes() method instead of using the indexOf() method to check whether the element is in the array.

let numbers = [1, 2, 3];
const state = numbers.indexOf(1) > -1 //  true
const state = numbers.includes(1)     //  true

3. Abbreviation of Array.map()

If you want to get the value of a specific field returned by the interface, you can use destructuring assignment and object abbreviation methods to abbreviate the map method.
For example, if the interface returns data, if you only want the id and name in the data, you can use the following abbreviation.

// 接口返回数据
res = [{
    
    
  id: 1,
  name: '张三',
  age: 20,
  sex: 0
}, {
    
    
  id: 2,
  name: '李四',
  age: 24,
  sex: 1
}]
// 第一种方法:箭头函数、返回对象
const list= res.map(v => ({
    
    id: v.id, name: v.name}))
// 第二种方法:箭头函数、 解构赋值
const list= res.map(({
     
     id, name}) => ({
    
    id, name}))

4. Comma operator (,)

逗号( , )运算符对它的每个操作数从左到右求值,并返回最后一个操作数的值。这让你可以创建一个复合表达式,其中多个表达式被评估,复合表达式的最终值是其成员表达式中最右边的值。这通常用于为 for 循环提供多个参数。

// 简化前
const list= arr => {
    
    
  arr.push('张三')
  return arr
}
console.log(list([1,2])) // 输出:[1, 2, '张三']

This code needs to return the modified array, which cannot be done directly return arr.push('a'), because the return value of push is the modified array length. At this time, it can be simplified into one line of code using the comma operator.

// 简化后
const list= arr => (arr.push('张三'), arr)
console.log(list([1,2])) // 输出:[1, 2, '张三']

5. Swap two variables without a third variable

In Js, you can split values ​​from an array using destructuring. Can be applied to swap two variables without a third variable

let x = 1;
let y = 2;

// 交换变量
[x, y] = [y, x];
console.log(x,y) //x:2,y:1

6. Remove duplicates from an array

Set in js has automatic deduplication function. Set is a collection that allows you to store only unique values. If you use the set method to deduplicate an array, first use new Set() to deduplicate it and convert it to an object, and then use Array.from() to convert the object back to the array.

//set特点:没有下标。自动去重
let arr = [1,2,3,2]
//数组转对象,这个过程实现去重
let setArr = new Set(arr)
console.log(setArr) //{1, 2, 3}

//需要利用Array.from将其转为数组
let newArr = Array.from(setArr)
console.log(newArr) // [1, 2, 3]
//简化后
let arr = [1,2,3,2];
let newArr = [...new Set(arr)];

6. Array dimensionality reduction

es6 flat()is used to "flatten" nested arrays into one-dimensional arrays. If the flat parameter is a few, then several layers of arrays will be flattened into one layer of arrays. This method returns a new array and has no effect on the original data.
If you are not sure how deep the array needs to be reduced, you can pass in the maximum value as the parameter Infinity. The default depth is 1.

const arr = [1, [2, [3, 4], 5], 6]
const flatArr = arr.flat(Infinity) // 输出 [1, 2, 3, 4, 5, 6]

Do you want to reduce the dimension of an array when using map, like this:

const arr = [1, 2, 3, 4]
const result = arr.map(v => [v, v * 2]).flat()  
console.log(result); // 输出 [1, 2, 2, 4, 3, 6, 4, 8]

js also provides a simpler method, which is flatMap(), which can be changed to this:

const result = arr.flatMap(v => [v, v * 2])

7. Quickly generate an array of 0-9

//传统写法
let arr = []
for(let i=0; i<10; i++){
    
    
   arr.push(i)
}
// 现在
const arr = [...new Array(10).keys()]

8. Logical empty assignment (??=)

Logical null assignment ??= The logical null assignment operator (x ??= y) only assigns a value to x if it is nullish (null or undefined).

const res ={
    
     num: 100 };
let text= res.num?res.num:0
//简化后
const res ={
    
     num: 100 };
let text= res.num??= 0;

9. Write conditional judgment code elegantly

Simple conditional judgment logic uses if else or ternary operators. You can know what they mean at a glance, but a large number of if elses and superimposed ternary operators are simply a nightmare for the catcher.

For example, if you encounter something like this in a real project,家人们,谁懂啊!

<div>{
    
    {
    
     info.status==1?'状态1':info.status==2?:'状态2':info.status==3?'状态3':info.status==4?'状态4':'状态5' }}</div>

For complex logic, it is recommended to use the object Map writing method, which is highly readable and comfortable to look at~~~

(1) Ordinary if else

let txt = '';
if (falg) {
    
    
 txt = "成功"
} else {
    
    
 txt = "失败"
}

(2) Ternary operator

let txt = flag ? "成功" : "失败";

(3) Multiple if else

let txt = '';
if (status == 1) {
    
    
 txt = "成功";
} else if (status == 2) {
    
    
 txt = "失败";
} else if (status == 3) {
    
    
 txt = "进行中";
} else {
    
    
 txt = "未开始";
}

(4)switch case

let txt = '';
switch (status) {
    
    
 case 1:
 txt = "成功";
 break;
 case 2:
 txt = "成功";
 break;
 case 3:
 txt = "进行中";
 break;
 default:
 txt = "未开始";
}

(5) Object writing method

const statusMap = {
    
    
 1: "成功",
 2: "失败",
 3: "进行中",
 4: "未开始"
}
//调用直接 statusMapp[status]

(6) Map writing method

const actions = new Map([
 [1, "成功"],
 [2, "失败"],
 [3, "进行中"],
 [4, "未开始"]
])
// 调用直接 actions.get(status)

10. Function conditional calling

// 冗余
function test1() {
    
    
  console.log('test1');
};
function test2() {
    
    
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
    
    
  test1();
} else {
    
    
  test2();
}

// 简化后
(test3 === 1? test1:test2)();

11. Use && for short circuit evaluation

Instead of checking if something is true with an if statement, you can use the && operator

var isReady = true;
function play(){
    
     
    console.log("hello!");
}
if(isReady){
    
     
    play();
}
//简化后
isReady && play();

12. Collect object values ​​into an array

Object.keys() collects all the keys of the object into a new array, and Object.values() collects all the values ​​of the object into a new array.

const info = {
    
     name: "张三", age: 35 };
let key = [];
let data = [];
for (let key in info) {
    
     
    key.push(key); 
    data.push(info[key]);
}
// SHORTHAND
const data = Object.keys(info);
const data = Object.values(info);

Guess you like

Origin blog.csdn.net/to_prototy/article/details/132301056