js common abbreviation skills (full of dry goods)

Share some of your commonly used js abbreviation skills, long-term updates, will focus on selecting some practical abbreviation skills to make your code more concise and elegant~

Here will only collect some usages that most people don’t know, but it can really improve your coding skills, like the basic shorthand syntax of ES6 or the ternary operator instead of those I think are the basics, there is no need to waste energy writing here if else.

Also recommend a practical website 1loc.dev that implements a method with only one line of code

Simplify if-else with || or ?? operators

Logical or operator ||, it should be noted here that 0and ''will also be considered false

If ||the previous value is 0 '' false null undefined NaNany one of them, return ||the following value directly

function(obj){
  var a = obj || {}
}
// 等价于 =>>
function(obj){
  var a;
  if(
    obj === 0 || 
    obj === "" || 
    obj === false || 
    obj === null || 
    obj === undefined ||
    isNaN(obj)
  ){
     a = {}
   } else {
     a = obj;
  }
}

The null coalescing operator ??returns the right side if the left side is not defined. If yes, return left.

This method is very practical, sometimes just want to judge whether a field has a value, instead of treating an empty string or 0 as false

function(obj){
  var a = obj ?? {}
}
// 等价于 =>>
function(obj){
  var a;
  if(
    obj === null || 
    obj === undefined
  ){
     a = {}
   } else {
     a = obj;
  }
}

Judgment that the input box is not empty (sometimes you don’t want to treat 0 as false, you can use this method. For example, a score of 0 is also a value, in this case it cannot be considered false)

if(value !== null && value !== undefined && value !== ''){}
// 等价于 ==>
if((value ?? '') !== ''){}

The correct usage posture of includes

In the above logical or operator ||code segment, there is an if judgment that is relatively long, and it can includesbe used to

if(
  obj === 0 || 
  obj === "" || 
  obj === false || 
  obj === null || 
  obj === undefined
){
  // ...
}

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

Optional chaining (?.) to prevent crashes

The optional chaining operator ?. will raise an error if it accesses an undefined property. This is where optional chaining comes in. 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 student = {
  name: "lwl",
  address: {
    state: "New York"
  },
}

// 一层一层判断
console.log(student && student.address && student.address.ZIPCode) // 输出:undefined
// 使用可选链操作符
console.log(student?.address?.ZIPCode) // 输出:undefined

The optional chaining operator can also be used in method calls. If the method exists, it will be called, otherwise it will be returned  undefined. For example:

const obj = {
  foo() {
    console.log('Hello from foo!')
  }
}

obj.foo?.() // 输出:'Hello from foo!'
obj.bar?.() // 输出:undefined,因为 bar 方法不存在

Likewise, arrays can also be used. For example:

const arr = [1, 2, 3, 4]

console.log(arr[0]) // 输出:1
console.log(arr[4]) // 输出:undefined

// 使用可选链运算符
console.log(arr?.[0]) // 输出:1
console.log(arr?.[4]) // 输出:undefined
console.log(arr?.[0]?.toString()) // 输出:'1'

Logical empty assignment (??=)

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

const a = { duration: 50 };

a.duration ??= 10;
console.log(a.duration);
// expected output: 50

a.speed ??= 25;
console.log(a.speed);
// expected output: 25

Quickly generate an array of 1-10

Generate 0-9, using the subscript value of the array

// 方法一
const arr1 = [...new Array(10).keys()]
// 方法二
const arr2 = Array.from(Array(10), (v, k) => k)

Generate 1-10, through the characteristics of map

const arr2 = [...Array(10)].map((v, i) => i + 1)

Quickly generate an array of 10 zeros

const arr = new Array(10).fill(0)

Quickly generate an array of 10 [] (two-dimensional array)

Note: Two-dimensional arrays cannot be written directly new Array(10).fill([])(that is, the fill method cannot pass reference-type values, nor can it be []replaced ), because passing in reference-type values ​​will cause each array to point to the same address. When one data is changed, other data will also change. For details, see mdn official instructionsnew Array()fill

// 错误写法
const arr = new Array(10).fill([]) // 注意这是错误写法,不要这么写
// 正确写法
const arr = new Array(10).fill().map(() => new Array())

Array dimensionality reduction

Are you still using recursion to reduce the dimensionality of a multidimensional array? If so, then you should know about the flat() method of es6.

If you are not sure how deep the array needs to be reduced, you can pass in the maximum value as a parameter Infinity, and the default value depth is 1

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

Do you mapwant to reduce the dimension of the array when using it? Something 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]

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

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

remove duplicates from array

In JavaScript, a Set is a collection that allows you to store only unique values. This means removing any duplicate values.

So, to remove duplicates from an array, you can convert it to a collection and then back to an array.

const numbers = [1, 1, 20, 3, 3, 3, 9, 9];
const uniqueNumbers = [...new Set(numbers)]; // -> [1, 20, 3, 9]

How does it work?

  1. new Set(numbers)Create a set from a list of numbers. Creating a collection automatically removes all duplicate values.

  2. The spread operator ...converts any iterable object into an array. This means converting the collection back to an array.[...new Set(numbers)]

Swap two variables without a third variable

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

Relatively simple, es6 syntax

let x = 1;
let y = 2;

// 交换变量
[x, y] = [y, x];

Collect the values ​​of the object into an array

Used Object.values()to collect all values ​​of an object into a new array

const info = { name: "Matt", country: "Finland", age: 35 };

// LONGER FORM
let data = [];
for (let key in info) {
  data.push(info[key]);
}

// SHORTHAND
const data = Object.values(info);

Exponential operator (not used much)

Are you Math.pow()used to raising a number to a power? Did you know you can use **operators too?

Although it can be shortened, I still recommend writing it Math.pow()as a method, the code is more semantic.

Note: **The operator requires the operand to be a numeric type, but it can also work normally in js.

Math.pow(2, 3); // 输出: 8 
2 ** 3; // 输出: 8 

Math.pow(4, 0.5); // 输出: 2 
4 ** 0.5; // 输出: 2 

Math.pow(3, -2); // 输出: 0.1111111111111111 
3 ** -2; // 输出: 0.1111111111111111 

Math.pow('2', '3'); // 输出: 8 (参数被自动转换为数字) 
'2' ** '3'; // js中输出: 8,其他语言可能报错

Shorthand for Math.floor() (not used much)

Rounding down Math.floor()is nothing new. But did you know you can also use ~~operators?

Although the above can be abbreviated, I still recommend writing it as Math.floor()a method, the code is more semantic.

Note: For positive numbers, both directly remove the decimal places, but for negative numbers, they Math.floor()are rounded down, ~~and only the decimal places are still removed, and the integer places remain unchanged. Please see the output below:

Math.floor(3.14); // 输出: 3 
Math.floor(5.7); // 输出: 5 
Math.floor(-2.5); // 输出: -3 
Math.floor(10); // 输出: 10

~~3.14; // 输出: 3 
~~5.7; // 输出: 5 
~~(-2.5); // 输出: -2 
~~10; // 输出: 10

comma operator (,)

The comma (  , ) operator evaluates each of its operands from left to right and returns the value of the last operand. This lets you create a compound expression where multiple expressions are evaluated, and the final value of the compound expression is the rightmost value of its member expressions. This is often used to  for provide multiple arguments to a loop.

Here I will only talk about the technique of using the comma operator to simplify the code when the function returns. For other usages, please click directly to view the official documentation.

Take a simple example:

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

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

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

Shorthand for Array.map()

For example, if you want to get the value of a specific field returned by the interface, you can use the destructuring assignment and the shorthand method of the object to abbreviate the map method. For a detailed explanation, please move to the js map method application scene processing object array.

idFor example, the interface returns data. At this time, if you only want the sum in the data name, you can use the following abbreviation.

// 接口返回数据
res = [{
  id: 1,
  name: 'zhangsan',
  age: 16,
  gender: 0
}, {
  id: 2,
  name: 'lisi',
  age: 20,
  gender: 1
}]

// 第一种方法:箭头函数、 解构赋值
const data = res.map(({id, name}) => ({id, name}))
// 第二种方法:箭头函数、返回对象(相对更容易理解)
const data = res.map(v => ({id: v.id, name: v.name}))

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/131843058