4, digital
4.1 different notation
ES6 added a different writing hexadecimal format, parameter passing in the background when to pay attention to this.
29 // 10 decimal 035 // octal 29 original manner 0o35 // octal 29 for ES6 manner 0x1d @ 16 hexadecimal 29 0b11101 @ 2 29 hex
4.2 accurate to the specified number of decimal places
Rounds a number to the specified decimal place. Use Math.round()
and templates literal rounds the number to the specified decimal place. The second parameter is omitted decimals
, the number will be rounded to an integer.
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`) round(1.345, 2) // 1.35 round(1.345, 1) // 1.3
4.3 Operation complementary digital 0
Thanks friends @JserWang @vczhan offer this little trick
Sometimes such as display time when sometimes need a digital display into two, this time you need to fill 0 operation, use slice
and string padStart
methods
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, the array
5.1 reduce method while achieving map and filter
Suppose there are a number of columns, each item you want to update it (map functions) and screened part (filter function). If the filter is to use the map and then, you need to traverse the array twice.
In the following code, we will double the value of the number of the column, and then pick out 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]
The number of the same item in the array of statistics 5.2
Many times, you want to count the number of recurring items in the array is then represented by an object. Then you can use this approach to reduce the array.
The following code would count the number of each vehicle is then represented by a total number of objects.
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 parameter values used to exchange deconstruction
Sometimes you will function returns multiple values in one array. We can use an array to get deconstructed in which each value.
let param1 = 1; let param2 = 2; [param1, param2] = [param2, param1]; console.log(param1) // 2 console.log(param2) // 1
Of course, we have a lot of value for the exchange of other ways:
var temp = a; a = b; b = temp b = [a, a = b][0] a = a + b; b = a - b; a = a - b
5.4 receiving a plurality of result returned by the function
In the following code, we get a message from / post, and then obtain the relevant comments / comments in. Since we are using async / await, function return value in an array. And after that we can use an array deconstruct the return value directly assigned to the corresponding variable.
async function getFullPost(){ return await Promise.all([ fetch('/post'), fetch('/comments') ]); } const [post, comments] = getFullPost();
5.5 tiling array to a specified depth
The use of recursion, for each depth level depth
is decremented by one. Use Array.reduce()
and Array.concat()
to incorporate elements or array. Under basic conditions, depth
equal to 1 to stop the recursion. The second parameter is omitted, depth
only the tile to a depth of 1 (single tile) is.
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 Object array of deconstruction
An array of objects may be deconstructed, you can easily acquire the n-th 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, the object
6.1 deconstruction delete unnecessary property
Sometimes you do not want to keep some object properties, perhaps because they contain sensitive information or just too big (just too big). You might enumerate the entire object and then delete them, but in fact simply need to assign these attributes to the variable useless, then you want to keep the useful part of the surplus can be used as a parameter.
The following code, we want to remove _internal and tooBig parameters. We can put them assigned to internal and tooBig variables, and then store the remaining attributes in cleanObject in 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 deconstruction nested objects function parameters
In the following code, engine car object in a nested object. If we are interested in vin attribute engine, the use of deconstruction assignment can easily get it.
the car = { model: 'bmw 2018' , engine: { v6: true , turbo: threaten , wine: 12345 } } const modelAndVIN = ({model, engine: {wine}}) => { console.log ( 'model : $ {model} wine: $ {wine} '); } ModelAndVIN (Car); // => model: bmw 2018 wine: 12345
7, code reuse
7.1 Object [key]
Although foo.bar
written as foo['bar']
is a common practice, but this approach forms the basis for the preparation of the code reusability. Many framework uses this method, such as verification form element.
Consider the following simplified example of this 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 complete the verification work. But when there are many forms, you'll need to verify the application, this time there will be different fields and rules. If you can build a common configuration validation functions at runtime, it would be a good choice.
// 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, with this verification function, we can reuse in all forms without having to write custom validation function for each form.