The following js tutorial column will introduce you to 8 tips and tricks for writing javascript code. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Recommended tutorial: "JavaScript Video Tutorial"
Sometimes you need to create an array within a certain range of numbers. For example, 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] // 也可以这样,但是大范围结果不稳定 Array.from({ length: end - start + 1 }, (_, i) => start + i);
Sometimes we need to put the values into the array first, and then use them as parameters of the function. transfer. Using ES6 syntax, you can extract values from an array using only the spread operator (...
): [arg1, arg2] => (arg1, arg2)
.
const parts = { first: [0, 2], second: [1, 3], }; ["Hello", "World", "JS", "Tricks"].slice(...parts.second); // ["World", "JS", "Tricks"]
This technique applies to any function, please continue to article 3.
When you need to find the maximum or minimum value of a number in the array, you can do as follows :
// 查到元素中的 y 位置最大的那一个值 const elementsHeight = [...document.body.children].map( el => el.getBoundingClientRect().y ); Math.max(...elementsHeight); // 输出最大的那个值 const numbers = [100, 100, -1000, 2000, -3000, 40000]; Math.min(...numbers); // -3000
Array has a method called Array.flat
, which requires a depth Parameter to flatten nested arrays (default is 1). But what if you don’t know the depth? At this time, you only need to use Infinity
as a parameter. There is also a useful flatMap method.
const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]; arrays.flat(Infinity); // [ 10, 50, 100, 2000, 3000, 40000 ]
If there is unpredictable behavior in the code, the consequences are unpredictable, so it needs to be dealt with.
For example, when the property you want to get is undefined
or null
, you will get a TypeError
error.
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
You can avoid it this way
const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}; console.log(found.name); // undefined
But it depends on the situation , there is no problem at all for processing small-scale code. It doesn't take much code to handle it.
In ES6, you can treat Template literals as without parentheses function parameters. This is useful when 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
Variables can be swapped easily by destructuring assignment syntax.
let a = "hello"; let b = "world"; // 错误 ❌ a = b b = a // { a: 'world', b: 'world' } // 正确 ✅ [a, b] = [b, a]; // { a: 'world', b: 'hello' }
Sometimes we need to mask part of the string, of course not just for passwords. In the following code, substr(-3)
is used to get a part of the string, that is, 3 characters forward from the end of the string, and then fill the remaining positions with your favorite characters (for example, use *
)
const password = "hackme"; password.substr(-3).padStart(password.length, "*"); // ***kme
When coding, you also need to keep the code clean, pay attention to accumulating the skills used in coding, and pay attention to the new features of JavaScript.
Original address: https://dev.to/gigantz/9-javascript-tips-tricks-to-code-like-a-wizard-559i
Author: Orkhan Jafarov
Translation address: https://segmentfault.com/a/1190000030697379
For more programming-related knowledge, please visit: Programming Course! !
The above is the detailed content of 8 Tips and Tricks for Writing Excellent JS Code (Share). For more information, please follow other related articles on the PHP Chinese website!