The New Year is almost here, share 25 JS practical tips for everyone

This article mainly introduces some tips used in JS, which can improve happiness in daily Coding, and will be updated from time to time~

  1. Type coercion

1.1 String is forced to be converted to a number

You can use *1 to convert to a number (actually call the .valueOf method)

Then use Number.isNaN to determine whether it is NaN, or use a!==a to determine whether it is NaN, because NaN!==NaN

'32' * 1 //
32'ds' * 1 // NaN
null * 1 // 0
undefined * 1 // NaN
1 * {valueOf: ()=>'3'} // 3
Commonly used: You can also use + To convert the string to a number

  • ‘123’ // 123
  • 'ds' // NaN
  • ‘’ // 0
  • null // 0
  • undefined // NaN
  • {valueOf: ()=>'3'} // 3
    1.2 Forcibly convert object to string

You can use the string + Object method to convert the object into a string (actually call the .toString() method)

'the Math object:' + Math // "the Math object:[object Math]"
'the JSON object:' + JSON // "the JSON object:[object JSON]" of
course can also override the toString and valueOf methods of the object Custom object type conversion:

2 * {valueOf: ()=>'3'} //
6'J' + {toString: ()=>'S'} // "JS"
"Effective JavaScript" P11: When + is used in concatenating strings When an object has both a toString method and a valueOf method, JS solves this ambiguity by blindly using the valueOf method.

The object is forced to be converted to a number through the valueOf method, and to a string through the toString method

'' + {toString:()=>'S',valueOf:()=>'J'} // J
I am an old web front-end programmer who has been engaged in development for many years. I am currently resigning and working on my own web Front-end private customized courses. At the beginning of this year, I spent a month compiling a web front-end learning dry goods that is most suitable for learning in 2019. The practical learning materials from the most basic HTML+CSS+JS to HTML5 projects are organized and sent to Every front-end partner, if you want to get it, you can add my web front-end exchange qun, [six zero] + [six one zero] + [one five one], download directly in the group, have any for learning web front-end Questions (learning methods, learning efficiency, how to get a job) can ask me.

Use Boolean to filter all false values ​​in the array

We know that there are some false values ​​in JS: false, null, 0, "", undefined, NaN, how to quickly filter the false values ​​in the array, you can use the Boolean constructor to perform a conversion

const compact = arr => arr.filter(Boolean)
compact([0, 1, false, 2,'', 3,'a','e' * 23, NaN,'s', 34]) // [ 1, 2, 3,'a','s', 34]
1.4 Double bit operator~~

You can use two-bit operators to replace Math.floor() for positive numbers and Math.ceil() for negative numbers. The advantage of the double-negation positioning operator is that it performs the same operation faster.

Math.floor(4.9) === 4 //true
// Abbreviated as:
~~4.9 === 4 //true
But note that for positive numbers~~ The result of the operation is the same as that of Math.floor() , And for negative numbers, the result of the operation is the same as Math.ceil():

~~4.5 // 4
Math.floor(4.5) // 4
Math.ceil(4.5) // 5

~~-4.5 // -4
Math.floor(-4.5) // -5
Math.ceil(-4.5) // -4
1.5 short-circuit operator

We know that logical AND && and logical OR || are short-circuit operators. The short-circuit operator is a left-to-right operation in which the former meets the requirements, and the latter is no longer executed;

It can be understood as:

&& is a false operation, which is judged from left to right. If a false value is encountered, the false value will be returned and will not be executed in the future, otherwise the last true value will be returned

||In order to take the truth operation, judge from left to right, if a true value is encountered, it will return the true value and will not be executed in the future, otherwise it will return the last false value
let param1 = expr1 && expr2
let param2 = expr1 || expr2
| Operator | Example | Description |

| — | — | — |

| && | expr1&&expr2 | If expr1 can be converted to false, return expr1, otherwise return expr2. Therefore, when used in a Boolean environment, return true if both operation results are true, otherwise return false. |

| || | expr1||expr2 | If expr1 can be converted to true, return expr1, otherwise return expr2. Therefore, when used in a boolean environment (in the conditional judgment of if), as long as one of the two operation results is true ,Returns true; if the results of both operations are both false, return false. |

|! | !expr | If a single expression can be converted to true, return false, otherwise return true. |

Therefore, it can be used to do many interesting things, such as assigning initial values ​​to variables:

let variable1
let variable2 = variable1 ||'foo'
If variable1 is true, it will return directly, and the short circuit will not be returned. If it is false, it will return the following foo.

It can also be used to make simple judgments instead of lengthy if statements:

let variable = param && param.prop
If param is true, return the param.prop property, otherwise return the false value of param, so that in some places it is prevented from taking its properties when param is undefined to cause an error.

1.6 Arrangement | 0

For a number |0 can be rounded, and negative numbers are also applicable, num|0

1.3 | 0 // 1
-1.9 | 0 // -1
1.7 Determine odd and even number &1

For a number &1, you can determine the odd and even numbers, and the same applies to negative numbers, num&1

const num=3;
!!(num & 1) // true
!!(num% 2) // true
2. Function

2.1 Function default values

func = (l, m = 3, n = 4) => (l * m * n);
func(2) //output: 24
Note that the default parameters will be used when the incoming parameters are undefined or not. But passing in null will still overwrite the default parameters.

2.2 Mandatory parameters

By default, if you don't pass a value to the function parameter, JS will set the function parameter to undefined. Some other languages ​​will issue warnings or errors. To perform parameter assignment, you can use an if statement to throw an undefined error, or you can use mandatory parameters.

mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory( )) => {// If no parameters are passed here, the mandatory function will be executed and an error will be reported return bar ; } 2.3 Implicit return value





The return value is the keyword we usually use to return the final result of the function. An arrow function with only one statement can return the result implicitly (the function must omit the braces {} in order to omit the return keyword).

To return multiple lines of statements (such as object text), you need to use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.

function calcCircumference(diameter) { return Math.PI * diameter } // Abbreviated as: calcCircumference = diameter => ( Math.PI * diameter; ) 2.4 Lazy loading function






In a certain scenario, there is a judgment statement in our function. This judgment basis generally does not change during the entire project operation. Therefore, the judgment branch will only run a specific branch during the entire project operation period. Then you can consider lazy loading functions.

function foo(){
if(a !== b){
console.log(‘aaa’)
}else{
console.log(‘bbb’)
}
}

// After optimization
function foo(){ if(a != b){ foo = function(){ console.log('aaa') } }else{ foo = function(){ console.log('bbb') } } return foo(); } Then this method will be overwritten after the first run, and the judgment will not be executed the next time it is run. Of course, there is only one judgment. If there are many judgments and branches are more complicated, the resources saved are still considerable.











2.5 One-time functions

Similar to the above lazy loading function, you can overwrite the current function in the function body, then you can create a one-time function. The code before reassignment is equivalent to only running once, which is suitable for running some that only need to be executed once. Initialization code

var sca = function() {
console.log(‘msg’)
sca = function() {
console.log(‘foo’)
}
}
sca() // msg
sca() // foo
sca() // foo
3. 字符串

3.1 String comparison time sequence

Strings can be used to compare chronological order:

var a = “2014-08-08”;
var b = “2014-09-09”;

console.log(a>b, a<b); // false true
console.log("21:00"<"09:10"); // false
console.log("21:00"<"9: 10”); // true time format pay attention to 0
because the string comparison size is based on the charCode of each character of the string from left to right, but so pay special attention to the time format pay attention to 0

  1. digital

4.1 Different base representations

ES6 has added different hexadecimal writing formats. Pay attention to this when transferring parameters in the background.

29 // Decimal
035 // Octal 29 The original method
0o35 // Octal 29 ES6 method
0x1d // Hexadecimal 29
0b11101 // Binary 29
4.2 Accurate to the specified number of decimals

Round the number to the specified number of decimal places. Use Math.round() and template literals to round the number to the specified number of decimal places. Omit the second parameter decimals, and the number will be rounded to an integer.

const round = (n, decimals = 0) => Number(${Math.round( n e {n}e n e {decimals})}e-${decimals})
round(1.345, 2) // 1.35
round(1.345, 1) // 1.3
4.3 Number complement 0 operation

Thanks to netizens @JserWang @vczhan for providing this tip

Sometimes, for example, when displaying the time, sometimes it is necessary to display a digit as two digits. At this time, it is necessary to add 0 operation, and you can use the padStart method of slice and string.

const addZero1 = (num, len = 2) => ( 0${num}) .slice (-len)
const addZero2 = (num, len = 2) => ( ${num}) .padStart (len, '0')
addZero1 (3) // 03

addZero2(32,4) // 0032
5. Array

5.1 The reduce method implements map and filter at the same time

Suppose there is a series of numbers, and you want to update each item (the function of the map) and then filter out a part (the function of the filter). If you use map first and then filter, you need to traverse the array twice.

In the following code, we double the values ​​in the number sequence, and then select those numbers greater than 50.

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => { num = num * 2; if (num> 50) { finalList.push(num); } return finalList; }, []); doubledOver50; // [60, 80] 5.2 Count the number of identical items in the array







Many times, you want to count the number of repeated items in the array and then use an object to represent it. Then you can use the reduce method to process this array.

The following code will count the number of each type of car and then use an object to represent the total.

var cars = ['BMW','Benz','Benz','Tesla','BMW','Toyota'];
var carsObj = cars.reduce(function (obj, name) { obj[name] = obj[ name]? ++obj[name]: 1; return obj; }, {}); carsObj; // => {BMW: 2, Benz: 2, Tesla: 1, Toyota: 1} 5.3 Use destructuring to exchange parameters Numerical value




Sometimes you put multiple values ​​returned by a function in an array. We can use array destructuring to get each of these values.

let param1 = 1;
let param2 = 2;
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1Of
course we have many other ways to exchange values :

var temp = a; a = b; b = temp
b = [a, a = b][0]
a = a + b; b = a-b; a = a-b
5.4 Receive multiple results returned by the function

In the code below, we get a post from /post, and then get related comments in /comments. Since we are using async/await, the function puts the return value in an array. After destructuring the array, we can assign the return value directly to the corresponding variable.

async function getFullPost(){ return await Promise.all([ fetch('/post'), fetch('/comments') ]); } const [post, comments] = getFullPost(); 5.5 Tile the array to the specified depth






Using recursion, decrement depth by 1 for each depth level. Use Array.reduce() and Array.concat() to merge elements or arrays. In the basic case, depth equals 1 to stop recursion. Omit the second parameter, depth can only be tiled to a depth of 1 (single-layer tile).

const flatten = (arr, depth = 1) =>
depth != 1
? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
: arr.reduce((a, v) => a.concat(v), []);
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
5.6 数组的对象解构

Arrays can also be deconstructed by objects, which makes it easy to get the nth value of the array

const csvFileLine = ‘1997,John Doe,US,[email protected],New York’;
const { 2: country, 4: state } = csvFileLine.split(’,’);

country // US
state // New Yourk
6. 对象

6.1 Use destructuring to remove unnecessary attributes

Sometimes you don't want to keep certain object properties, perhaps because they contain sensitive information or are just too big. You might enumerate the entire object and delete them, but in fact you just need to simply assign these useless properties to variables, and then use the useful parts you want to keep as the remaining parameters.

In the following code, we want to delete the _internal and tooBig parameters. We can assign them to internal and tooBig variables, and then store the remaining properties in cleanObject for later use.

let {_internal, tooBig,… cleanObject} = {el1: '1', _internal: “secret”, tooBig: {}, el2: '2', el3: '3'};

console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
6.2 Deconstruct nested objects in function parameters

In the following code, engine is an object nested in the object car. If we are interested in the vin attribute of engine, we can easily get it using destructuring assignment.

var car = {
model: ‘bmw 2018’,
engine: {
v6: true,
turbo: true,
vin: 12345
}
}
const modelAndVIN = ({model, engine: {vin}}) => {
console.log(model: ${model} vin: ${vin});
}
modelAndVIN(car); // => model: bmw 2018 vin: 12345
7. 代码复用

7.1 Object [key]

Although it is a common practice to write foo.bar as foo['bar'], this practice forms the basis for writing reusable code. Many frameworks use this method, such as element form validation.

Consider the following simplified example of the verification function:

function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'}) ); // true The above function perfectly completes the verification work. But when there are many forms, validation needs to be applied, and there will be different fields and rules at this time. It would be a good choice if you could build a universal verification function that is configured at runtime.







// object validation rules
const schema = {
first: {
required:true
},
last: {
required:true
}
}

// universal validation function
const validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true ; } console.log(validate(schema, (first:'Bruce'))); // false console.log(validate(schema, (first:'Bruce',last:'Wayne'))); // true Now that we have this verification function, we can reuse it in all forms without writing a custom verification function for each form.












Insert picture description here

Add the number complement 0 operation provided by enthusiastic netizens.
Add 3.1, string comparison time sequence.
Thank you netizens~~ The performance is the same as Math.ceil() when the number is negative. The
New Year is about to share 25 JS practical tips for everyone
. Most of the posts on the Internet The depths are different, and even some are inconsistent. The article below is a summary of the learning process. If you find errors, please leave a message to point out~

Guess you like

Origin blog.csdn.net/ZYDX18984003806/article/details/103603258
Recommended