JS Practical Tips

1. The application of reduce

reduce introduction

The main function of reduce is similar to accumulation. The final result is recorded by a value, and this value is continuously put into the traversal, and finally the required final result is returned.
reduce((previousValue, currentValue, currentIndex, array) => { /* … */ } , initialValue) The
four parameters in the first parameter method are the value of the previous record, the current traversal item, the current traversal index, and the array itself. The parameter is to give pre an initial value.

scenes to be used

const arr = [1,2,3,4,5]
// 1、累加(给一个初始值2)
const test =arr.reduce((pre,cur)=>{
    
    
  return pre+cur;
},2)
// 输出17

// 2、找出最大值
const test2=arr.reduce((pre,cur)=>pre>cur?pre:cur)
// 输出5

When the array items are numbers, Math.max(...arr) can also be used to find the maximum and minimum values ​​and even look more elegant. But the limitation is that the type is a number, and when the array item is of other types (such as finding the maximum value of a certain attribute in an object array), reduce can provide a better solution.

2. Initialize the two-dimensional array

I encountered the scene of initializing a two-dimensional array in the process of actually writing the code. At that time, I also wanted to use fill to realize it, but it failed. The reason is that I directly put [] and pointed to the actual array object, which caused everything to fail. It points to the same empty array, which can be implemented more elegantly with map after reference.

const secondArr = Array(5).fill(0).map(()=>Array(0))
// 输出
// 0: []
// 1: []
// 2: []
// 3: []
// 4: []
// length: 5

To initialize a two-dimensional array with known rows, you only need to fill the outer layer with 0, and then traverse each row and return an empty array.

3. Filter out false values ​​from the array

Filter out all false values ​​with Boolean function: 0, undefined, null, false, "", ''. Disadvantages: 0 will also be filtered out, and the presence of the number 0 may be required for numeric arrays.

const arr=[0,3,2,'',false,null]
const arrFilter = arr.filter(Boolean)
console.log(arrFilter)
//输出[3,2]

4. Null coalescing operator

The null coalescing operator (??) is a logical operator that returns its right-hand operand if its left-hand operand is null or undefined, and its left-hand operand otherwise.

const foo = null ?? 'my school';
// 输出: "my school"
const baz = 0 ?? 42;
// 输出: 0

5. Convert decimal to binary or hexadecimal

const num = 10;
num.toString(2);
// 输出: "1010"
num.toString(16);
// 输出: "a"
num.toString(8);
// 输出: "12"

Guess you like

Origin blog.csdn.net/m0_46550764/article/details/127138334