9 tips for daily development of JavaScript

  • 2021-08-28 19:23:17
  • OfStack

1. Generate a specified range of numbers

In some cases, we will create an array between two numbers. Suppose we want to determine whether someone's birthday is in a certain range of years, then here is a very simple way to achieve it


let start = 1900, end = 2000;
[...new Array(end + 1).keys()].slice(start);
// [ 1900, 1901, ..., 2000]
//  There is also this way, but it is not stable for a large range 

Array.from({ length: end - start + 1 }, (_, i) => start + i);

2. Use an array of values as an argument to a function

In some cases, we need to collect the values into an array and pass them as arguments to the function. With ES6, you can use the extension operator (...) and derive from [arg1, arg2] > (arg1, arg2):


const parts = {
 first: [0, 2],
 second: [1, 3],
}

["Hello", "World", "JS", "Tricks"].slice(...parts.second)
// ["World", "JS"]

3. Use values as arguments to the Math method

When we need to use Math. max or Math. min in an array to find the maximum or minimum value, we can do this as follows:


const elementsHeight = [...document.body.children].map(
 el => el.getBoundingClientRect().y
);
Math.max(...elementsHeight);
// 474

const numbers = [100, 100, -1000, 2000, -3000, 40000];
Math.min(...numbers);
// -3000

4. Merge/flatten arrays within arrays

Array has a good method, called Array. flat, which requires an depth parameter to indicate the depth of array nesting, and the default value is 1. However, if we don't know what to do with the depth, we need to flatten it all, and we only need to take Infinity as a parameter to


Related articles: