Mall source code cloud address:github.crmeb.net/u/lin

1. Generate numbers in the specified range

Sometimes you need to create an array within a range of numbers. Like when choosing a birthday. Here’s the simplest way to do it.

let start = 1900, end = 2000; [...new Array(end + 1).keys()].slice(start); Array.from({length: end-start + 1}, (_, I) => start + I);Copy the code

2. Take the values in the value array as arguments to the function

Sometimes we need to put values in an array and then pass them as arguments to a function. Using ES6 syntax, you can simply rely on the extension operator (…). We can extract the value from the array: [arg1, arg2] => (arg1, arg2).

const parts = { first: [0, 2], second: [1, 3], }; ["Hello", "World", "JS", "Tricks"].slice(... parts.second); // ["World", "JS", "Tricks"]Copy the code

This technique can be applied to any function, so move on to # 3.

3. Take the values in the value array as arguments to the Math method

When you need to find the maximum or minimum value of a number in an array, you can do something like this:

/ / check to the element of the y position of the largest it a value const elementsHeight = [.... the document body. Children]. The map (el = > el. GetBoundingClientRect (.) y); Math.max(... elementsHeight); Const numbers = [100, 100, -1000, 2000, -3000, 40000]; // Const numbers = [100, 100, -1000, 2000, -3000, 40000]; Math.min(... numbers); / / - 3000Copy the code

4. Flatten the nested array

Array has a method called array.flat, which requires a depth parameter to flatter the nested Array (default is 1). But if you don’t know the depth, just use Infinity as an argument. There is also a nice flatMap method.

const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]; arrays.flat(Infinity); // [10, 50, 100, 2000, 3000, 40000]Copy the code

5. Prevent code crashes

If you have unpredictable behavior in your code, the consequences are unpredictable, so you need to deal with it. For example, you get TypeError when the attribute you want is undefined or null. If your project code does not support optional chaining, you can do this:

const found = [{ name: "Alex" }].find(i => i.name === 'Jim');
console.log(found.name);
// TypeError: Cannot read property 'name' of undefined
Copy the code

That can be avoided

const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {};
console.log(found.name);
// undefined
Copy the code

It depends, though, and there’s nothing wrong with dealing with small code. It doesn’t take much code to handle it.

6. A good way to send a reference

In ES6, you can think of Template literals as arguments to unparenthesized functions. This is great for formatting or converting text.

const makeList = (raw) =>
  raw
    .join()
    .trim()
    .split("\\n")
    .map((s, i) => `${i + 1}. ${s}`)
    .join("\\n");

makeList`
Hello, World
Hello, World
`;

// 1. Hello
// 2. World
Copy the code

7. Swap variable values like a magic trick

By deconstructing the assignment syntax, variables can be easily swapped.

let a = "hello"; let b = "world"; / / error ❌ a = b, b = a / / {a: 'world' b: 'world'} / / correct ✅ [a, b] = [b, a]; // { a: 'world', b: 'hello' }Copy the code

8. Masking strings

Sometimes we need to mask part of the string, not just the password. Get the following part of the string by substr(-3), starting three characters from the end of the string, and filling the rest of the string with any character you like (for example, *)

const password = "hackme";
password.substr(-3).padStart(password.length, "*");
// ***kme
Copy the code

conclusion

You also need to keep your code clean when coding, pay attention to the accumulation of techniques used in coding, and pay attention to the new features of JavaScript.

Mall source code cloud address:github.crmeb.net/u/lin

Author: CRMEB Technical Team Link: juejin.cn/post/693350… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.