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);
// [1900, 1901..., 2000]

// This is possible, but the results are unstable on a large scale
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:

// Find the value with the largest y position in the element
const elementsHeight =  [...document.body.children].map(
  el= > el.getBoundingClientRect().y
);
Math.max(... elementsHeight);// Print the maximum value
const numbers = [100.100, -1000.2000, -3000.40000];
Math.min(... numbers);/ / - 3000
Copy 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' }

/ / ✅ correctly
[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.

Thank you for reading, if you are helpful, welcome to pay attention to “CRMEB” nuggets.

Code cloud has our open source mall project, knowledge payment project, JAVA version of the full open source mall system, study and study welcome to use, the old iron easily point a star bai, the boss reward fifty cents, points you twenty-five cents, 😂😂 pay attention to us to keep in touch!