Hello everyone, I am CUGGZ, a front-end chicken, today to share a few JavaScript development tips, I hope to help you ~

1. Initialize the array

If you want to initialize a one-dimensional array of a specified length and specify a default value, you can do this:

const array = Array(6).fill(' '); 
// ['', '', '', '', '', '']
Copy the code

If you want to initialize a two-dimensional array with a specified length and specify a default value, you can do this:

const matrix = Array(6).fill(0).map(() = > Array(5).fill(0)); 
// [[0, 0, 0, 0],
// [0, 0, 0, 0, 0]
// [0, 0, 0, 0, 0]
// [0, 0, 0, 0, 0]
// [0, 0, 0, 0, 0]
// [0, 0, 0, 0]]
Copy the code

2. Array summation, find the maximum value, minimum value

const array  = [5.4.7.8.9.2];
Copy the code

Array summation:

array.reduce((a,b) = > a+b);
Copy the code

Array maximum:

array.reduce((a,b) = > a > b ? a : b);

Math.max(... array)Copy the code

Array minimum:

array.reduce((a,b) = > a < b ? a : b);

Math.min(... array)Copy the code

Using the reduce method of arrays can solve many array evaluation problems.

3. Filter error values

If you want to filter the values of false, 0, null, and undefined in an array, you can do this:

const array = [1.0.undefined.6.7.' '.false];

array.filter(Boolean);
/ / [1, 6, 7)
Copy the code

4. Use logical operators

If you have a code that looks like this:

if(a > 10) {
    doSomething(a)
}
Copy the code

This can be overwritten using logical operators:

a > 10 && doSomething(a)
Copy the code

If the value of the && operator is false, it will short-circuit and terminate the execution of the statement. If true, the code after && continues and returns the return value of the code after it. Using this method can reduce a lot of if… The else.

5. Judgment simplification

If there is a judgment like this:

if(a === undefined || a === 10 || a=== 15 || a === null) {
    / /...
}
Copy the code

We can use arrays to simplify the logic:

if([undefined.10.15.null].includes(a)) {
    / /...
}
Copy the code

So it’s a lot cleaner, and it’s easy to expand, and if you still need to equal a, you just add it to the array.

6. Empty the array

If you want to empty an array, you can set the length of the array to 0:

let array = ["A"."B"."C"."D"."E"."F"]
array.length = 0 
console.log(array)  / / []
Copy the code

7. Calculate code performance

You can use the following operations to calculate the performance of your code:

const startTime = performance.now(); 
// Some programs
for(let i = 0; i < 1000; i++) {
    console.log(i)
}
const endTime = performance.now();
const totaltime = endTime - startTime;
console.log(totaltime); / / 30.299999952316284
Copy the code

8. Concatenate arrays

If we want to concatenate several arrays, we can use the extension operator:

const start = [1.2] 
const end = [5.6.7] 
const numbers = [9. start, ... end,8] // [9, 1, 2, 5, 6, 7, 8]
Copy the code

Or use the concat() method of arrays:

const start = [1.2.3.4] 
const end = [5.6.7] 
start.concat(end); // [1, 2, 3, 4, 5, 6, 7]
Copy the code

But with concat(), if the array to be merged is large, the concat() function consumes a lot of memory when creating a separate new array. You can use the following methods to merge arrays:

Array.push.apply(start, end)
Copy the code

This way you can use less memory to a large extent.

9. Object authentication

If we have an object like this:

const parent = {
    child: {
      child1: {
        child2: {
          key: 10}}}}Copy the code

Most of the time we will write this to avoid a level that does not exist to cause an error:

parent && parent.child && parent.child.child1 && parent.child.child1.child2
Copy the code

This makes the code look bloated, using JavaScript’s optional chain operator:

parent? .child? .child1? .child2Copy the code

This implementation and effect is the same as the long list above.

The optional chain operator also works with arrays:

const array = [1.2.3]; array? .5]
Copy the code

The optional chain operator allows us to read the value of a property located deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid. An error is not raised if the reference is null (or undefined), and the expression short-circuited returns undefined. When used with a function call, returns undefined if the given function does not exist.

10. Validate undefined and NULL

If you have code like this:

if(a === null || a === undefined) {
    doSomething()
}
Copy the code

If you need to verify that a value is equal to null or undefined, you can use the null value merge operator to simplify the above code:

a ?? doSomething()
Copy the code

Thus, the code following the control merge operator is executed only if a is undefined or null. Null-value merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand.

11. Array elements are converted to numbers

If you have an array and want to convert the elements of the array to numbers, you can use the map method:

const array = ['12'.'1'.'3.1415'.'10.01'];
array.map(Number);  // [12, 1, 3.1415, -10.01]
Copy the code

In this way, the map executes the Number constructor on each element of the array as it iterates through the array and returns the result.

12. Class array to array

You can convert class array arguments to an array using the following methods:

Array.prototype.slice.call(arguments);
Copy the code

In addition, you can use the extension operator to do this:

[...arguments]
Copy the code

13. Objects dynamically declare properties

If you want to dynamically declare attributes for an object, you can do this:

const dynamic = 'color';
var item = {
    brand: 'Ford',
    [dynamic]: 'Blue'
}
console.log(item); 
// { brand: "Ford", color: "Blue" }
Copy the code

14. Shorten the console. The log ()

Writing a lot of console.log() each time you debug can be cumbersome, so you can simplify this code by using the following form:

const c = console.log.bind(document) 
c(996) 
c("hello world")
Copy the code

So I’m just going to execute c every time.

15. Obtain query parameters

If we want to get the parameters in the URL, we can use the properties of the window object:

window.location.search
Copy the code

If a URL is www.baidu.com? Project =js&type=1 then the above operation will get? Project =js&type=1. If you want to get one of these parameters, you can do this:

let type = new URLSearchParams(location.search).get('type');
Copy the code

16. Round numbers

If we have a number that contains decimals, we want to eliminate decimals by using the math.floor, math.ceil, or math.round methods. You can actually use the ~~ operator to eliminate the decimal part of a number, which is much faster than the numeric methods.

~ ~3.1415926  / / 3
Copy the code

This operator can be used to convert a variable to a numeric type.

  • If it is a numeric string, it is converted to a pure number.
  • If the string contains a value other than a number, it is converted to 0;
  • If it is a Boolean, true returns 1 and false returns 0.

Besides this way, we can also use the bitwise and to realize the digital integral operation, you just need to behind the Numbers plus | 0:

23.9 | 0   / / 23
-23.9 | 0   / / - 23
Copy the code

This operation also directly removes the decimal following the number. This method is similar to the above method and performs much better than the JavaScript API.

17. Delete array elements

If we want to delete an element from an array, we can use delete to do so, but the deleted element will become undefined and will not disappear, and the execution will take a lot of time, which in most cases does not meet our requirements. So we can use the array’s splice() method to delete array elements:

const array = ["a"."b"."c"."d"] 
array.splice(0.2) // ["a", "b"]
Copy the code

18. Check whether the object is empty

If we want to check whether an object is empty, we can use the following method:

Object.keys({}).length  / / 0
Object.keys({key: 1}).length  / / 1
Copy the code

The object.keys () method is used to retrieve the keys of an Object and returns an array of those keys. If the returned array length is 0, the object must be empty.

19. Replace if/else with switch case

Switch case performs better than if/else and the code looks cleaner.

if (1 == month) {days = 31; }else if (2 == month) {days = IsLeapYear(year) ? 29 : 28; }else if (3 == month) {days = 31; }else if (4 == month) {days = 30; }else if (5 == month) {days = 31; }else if (6 == month) {days = 30; }else if (7 == month) {days = 31; }else if (8 == month) {days = 31; }else if (9 == month) {days = 30; }else if (10 == month) {days = 31; }else if (11 == month) {days = 30; }else if (12 == month) {days = 31; }Copy the code

Use the switch… Case to rewrite:

switch(month) {
        case 1: days = 31; break;
        case 2: days = IsLeapYear(year) ? 29 : 28; break;
        case 3: days = 31; break;
        case 4: days = 30; break;
        case 5: days = 31; break;
        case 6: days = 30; break;
        case 7: days = 31; break;
        case 8: days = 31; break;
        case 9: days = 30; break;
        case 10: days = 31; break;
        case 11: days = 30; break;
        case 12: days = 31; break;
        default: break;
}
Copy the code

It looks relatively neat. We can overwrite if… using arrays or objects, depending on the case. The else.

20. Get the last item in the array

If you want to get the last item in an array, you will often write:

const arr = [1.2.3.4.5];
arr[arr.length - 1]  / / 5
Copy the code

We can also use the array’s slice method to retrieve the last element of the array:

arr.slice(-1)
Copy the code

When we set the slice method to a negative value, we truncate the array values from the back of the array. If we want to truncate the last two values, we pass the argument -2.

21. Value is converted to a Boolean value

In JavaScript, the following values are converted to false when Boolean values are converted, and the other values are converted to true:

  • undefined
  • null
  • 0
  • 0
  • NaN
  • “”

Normally, if we want to convert an explicit value to a Boolean value, we use the Boolean() method. Actually we can use it!! Operator to convert a value to a Boolean value. We know, one! Is to convert an object to a Boolean and invert it. Two! Is invert a Boolean value, which is equivalent to converting a non-Boolean value to a Boolean value. This operation performs much faster than the Boolean() method because it is native to the computer: Boolean()

!!!!!undefined // false!!!!!"996"     // true!!!!!null      // false!!!!!NaN       // false
Copy the code

22. Format JSON code

You’ve probably all used the json.stringify method, which converts a JavaScript object or value to a JSON string. His grammar is as follows:

JSON.stringify(value, replacer, space)
Copy the code

It takes three arguments:

  • Value: The value to be serialized into a JSON string.
  • Replacer Optional: If this parameter is a function, each attribute of the serialized value is converted and processed by the function during serialization. If the parameter is an array, only the property names contained in the array will be serialized into the final JSON string; If this parameter is null or not provided, all attributes of the object are serialized.
  • Space Optional: Specifies a blank string for indentation, which is used to beautify the output (pretty-print). If the argument is a number, it represents how many Spaces there are; The upper limit is 10. If the value is less than 1, there are no Spaces. If the parameter is a string (the first 10 characters are taken when the string is longer than 10 characters), the string will be used as a space. If this parameter is not provided (or null), there will be no Spaces.

Typically, we write a parameter to convert a JavaScript object or value to a JSON string. As you can see, it also has two optional arguments, so we can format JSON code with these:

console.log(JSON.stringify({ alpha: 'A'.beta: 'B' }, null.'\t'));
Copy the code

The following output is displayed:

23. Avoid eval() and with()

  • With () inserts a variable in the global scope. Therefore, if another variable has the same name, it can cause confusion and overwrite the value.
  • Eval () is an expensive operation, and the script engine must convert the source code into executable code each time it is called.

24. Function arguments use objects instead of argument lists

When we use argument lists to pass arguments to functions, it’s fine if there are fewer arguments, but it’s more troublesome if there are more, because we have to pass arguments in the order of the argument list. If you write in TypeScript, you also need to write with optional arguments after required ones.

If our function has a lot of parameters, we can consider using the form of an object to pass the parameters. When passing the parameters in the form of an object, the optional parameters need not be passed last, and the order of the parameters does not matter. Content passed through objects is also easier to read and understand than argument lists.

Here’s an example:

function getItem(price, quantity, name, description) {}

getItem(15.undefined.'bananas'.'fruit')
Copy the code

Let’s use an object to pass a parameter:

function getItem(args) {
    const {price, quantity, name, description} = args
}

getItem({
    name: 'bananas'.price: 10.quantity: 1.description: 'fruit'
})
Copy the code

This is the end of today’s sharing, if you feel useful click a “like” bar! Rush performance at the end of the year, sprint 100W reading ~🤣