Written in the beginning

  • ES6 common but ignored methods series of articles, sorting out the author thinks that some daily development may use some methods, use skills and some application scenarios, details please see related content links, welcome to supplement exchange.

Related articles

  • ES6 Common but ignored methods (second bullet functions, arrays, and objects)
  • ES6 common but ignored methods (third bullet Symbol, Set, and Map)
  • ES6 commonly used but overlooked methods (fourth bullet Proxy and Reflect)
  • ES6 common but ignored methods (# 5 Promise and Iterator)
  • Common but ignored methods for ES6 (Generator 6)
  • ES6 Common but ignored methods (async)
  • ES6 Common but ignored methods (eighth bullet Class)
  • ES6 common but ignored methods (Module 9)
  • Common but ignored methods of ES6 (Development specification of the Tenth Bullet Project)
  • ES6 common but ignored method (eleventh bullet Decorator)
  • Common but overlooked approaches to ES6 (End game – Latest Proposal)

Deconstruction assignment

  • ES6- Destruct assignment of variables

Discard the value of an attribute that is not needed by an object

Const obj = {name: 'detanx', age: 24, height: 180} const obj = {name: 'detanx', age: 24, height: 180} otherObj } = obj; // otherObj => {name: 'detanx', age: 24}Copy the code

Discard unwanted items from the array

Const arr = ['detanx', 24, 180] // Const [name,...otherArr] = arr; // otherArr => [24, 180]Copy the code

Setting defaults

  • ES6Internally using the strict equality operator (= = =) to determine whether a position has a value. So, only if an array member is strictly equal toundefined, the default value takes effect. (An interview may come up)
const [x = 1] = [undefined];
// x 1
const [x = 1] = [null];
// x null
Copy the code
  • You can refer to other variables that destruct assignments, but that variable must already be declared.
let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError: y is not defined
Copy the code

Swap the values of two variables without requiring additional variables

let x = 1, y = 2;
[x, y] = [y, x]
// x: 2,y: 1
Copy the code

Gets the specified value

Function example() {return [1, 2, 3]; } let [a, b, c] = example(); Function example() {return {foo: 1, bar: 2}; } let { foo, bar } = example(); Import {clone} from '_lodash';Copy the code

string

  • ES6- String new method

includes

  • Determine whether the target character or string fragment exists in a string that needs to be usedindexOfThe return result is the location where the target first appeared, and there is no return- 1. In the actual scenario, we don’t need to go back to the position of the target in the string, we just need to determine whether the target is in the string, so we can useincludes. You can also take a second argument that indicates the position from left to right
'detanx'.includes('tan') // true
'detanx'.includes('tan',3) // false
Copy the code

Query the target character at the beginning or end of the string

  • str.startsWith(char[, pos])The querycharIs it the beginning of a string,posRepresents the position from left to right that counts as the starting position.
'detanx'.startsWith('tan', 2) // true
Copy the code
  • str.endsWith(char[, len])The querycharIs it a string,lenRepresents how many characters (length) are contained from left to right.
'detanx'.endsWith('tan', 5) // true
Copy the code

How many times the string is repeatedrepeat

  • How many times does the string repeat, receiving an argument
    1. When the parameter is greater than- 1And less than1Or forNaNas0
    2. Is greater than1And rounding down when it’s a decimal
    3. forinfinityOr less than- 1When an error
    4. Other types are converted to numbers
'detanx. Repeat (0) / / ""' detanx. Repeat (0.7) / /" "' detanx. Repeat (NaN) / /" "' detanx. Repeat (2) / /" detanxdetanx" 'detanx'.repeat({}) // "" 'detanx'.repeat([]) // "" 'detanx'.repeat(()=>{}) // ""Copy the code

String completion

  • Complete from the leftpadStartIf the length of the string is not long enough, you need to specify the start of the string. The default value of the second parameter is space.
Const x = 7 if(x < 10) String(x). PadStart (2,'0') // Replace end '04'. PadStart (10, 'YYYY-MM-DD'); // 'YYYY-MM-04'Copy the code
  • Complete from the rightpadEndIf the length of the string is not enough, you need to specify the end of the string.
'de'.padEnd(6, 'tanx'); // detanx
Copy the code

Go head or tail space

  • In addition to the space bar, these two methods apply to the header (or tail) of the stringtabInvisible whitespace characters such as keys and newlines are also valid.
  • The browser also deploys two additional methods,trimLeft()istrimStart()The alias,trimRight()istrimEnd()The alias.
// remove the header space 'detanx '. TrimStart (); // 'detanx ' ' detanx '.trimLeft(); // 'detanx '// remove trailing space 'detanx '. TrimEnd (); // ' detanx' ' detanx '.trimRight(); // ' detanx'Copy the code

Numerical extension

  • ES6- Numerical extension

isFinite

  • Used to check if a number is finite (finite(NoInfinityor-Infinity. Other types return directlyfalse, includingNaN.
Number.isFinite(15); / / true Number. IsFinite (0.8); // true Number.isFinite(NaN); // false Number.isFinite(Infinity); // false Number.isFinite(-Infinity); // false Number.isFinite('foo'); // false Number.isFinite('15'); // false Number.isFinite(true); // falseCopy the code

isInteger

  • Checks whether a value is an integer. Do not use this parameter if high data accuracy is requiredNumber.isInteger()Checks whether a value is an integer.
  • JavaScriptusingIEEE 754Standard, the value store is64Bit double – precision format, numerical accuracy can be up to53Binary bits (1A hidden bit and52Significant bits). If the precision of the value exceeds this limit, the 54th and subsequent bits are discarded, in which case,Number.isIntegerMiscalculation is possible.
/ / true Number. IsInteger (3.0000000000000002)Copy the code
  • This decimal is accurate to the decimal point16The number of decimal bits converted to binary is over53Two bits, leading to the last one2Be discarded.
  • If the absolute value of a number is less thanNumber. MIN_VALUE (5 e - 324)That is less thanJavaScriptThe minimum value that can be resolved is automatically converted to0.Number.isIntegerThey can misjudge.
Number.isInteger(5E-324) // false
Number.isInteger(5E-325) // true
Copy the code

isSafeInteger

  • Number.isSafeInteger()Is used to determine whether an integer falls inNumber.MAX_SAFE_INTEGERandNumber.MIN_SAFE_INTEGERBetween these two constants.
Number.isSafeInteger('a') // false Number.isSafeInteger(null) // false Number.isSafeInteger(NaN) // false Number.isSafeInteger(Infinity) // false Number.isSafeInteger(-Infinity) // false Number.isSafeInteger(3) // true Number.issafeinteger (1.2) // False Number.isSafeINTEGER (9007199254740990) // True Number.isSafeINTEGER (9007199254740992)  // false Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1) // false Number.isSafeInteger(Number.MIN_SAFE_INTEGER) // true Number.isSafeInteger(Number.MAX_SAFE_INTEGER) // true Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1) // falseCopy the code
  • Be careful when actually using this function. Verify that the result of an operation falls within the range of safe integers, not just the result of the operation, but each value participating in the operation.

Math.trunc

  • Math.truncThe () method is used to remove the fractional part of a number and return the integer part. The number,Math.truncInternal useNumberMethod converts it to a value first. Returns a null value and a value that cannot intercept an integerNaN.
Math.trunc(4.9) // 4 Math.trunc(-4.1) // -4 math.trunc (-0.1234) // -0 math.trunc ('123.456') // 123 Math.trunc(true) //1 Math.trunc(false) // 0 Math.trunc(null) // 0 Math.trunc(NaN); // NaN Math.trunc('foo'); // NaN Math.trunc(); // NaN Math.trunc(undefined) // NaNCopy the code
  • Analog implementation
Math.trunc = Math.trunc || function(x) {
  return x < 0 ? Math.ceil(x) : Math.floor(x);
};
Copy the code

Math.sign

  • Math.signThe method is used to determine whether a number is positive, negative, or zero. For non-numeric values, they are converted to numeric values first.
    1. Returns if the argument is a positive number+ 1;
    2. If argument is negative, return- 1;
    3. Parameters for0To return to0;
    4. Parameters for0To return to0;
    5. Other values, return NaN.
Math.sign(-5) // -1
Math.sign(5) // +1
Math.sign(0) // +0
Math.sign(-0) // -0
Math.sign(NaN) // NaN
Copy the code
  • If the parameter is not a value, it is automatically converted to a value. Returns values that cannot be converted to numeric valuesNaN.
Math.sign('')  // 0
Math.sign(true)  // +1
Math.sign(false)  // 0
Math.sign(null)  // 0
Math.sign('9')  // +1
Math.sign('foo')  // NaN
Math.sign()  // NaN
Math.sign(undefined)  // NaN
Copy the code
  • Analog implementation
Math.sign = Math.sign || function(x) { x = +x; // convert to a number if (x === 0 || isNaN(x)) { return x; } return x > 0 ? 1:1; };Copy the code

Math.cbrt

  • Math.cbrt()The cube root () method is used to calculate the cube root of a number.
Math.cbrt(-1) // -1 math.cbrt (0) // 0 math.cbrt (1) // 1 math.cbrt (2) // 1.2599210498948732Copy the code
  • For non-numerical values,Math.cbrt()The inside of the method is also used firstNumber()The method converts it to a value.
Math.cbrt('8') // 2
Math.cbrt('hello') // NaN
Copy the code
  • Analog implementation
Math.cbrt = Math.cbrt || function(x) {
  var y = Math.pow(Math.abs(x), 1/3);
  return x < 0 ? -y : y;
};
Copy the code

Math.hypot

  • Math.hypotMethod returns the square root of the sum of squares of all arguments.
Math.hypot(3, 4); // 5 Math.hypot(3, 4, 5); / / 7.0710678118654755 Math. The hypot (); // 0 Math.hypot(NaN); // NaN Math.hypot(3, 4, 'foo'); // NaN Math.hypot(3, 4, '5'); / / 7.0710678118654755 math.h hypot (3); / / 3Copy the code
  • In the code above,3Omega squared plus4Omega squared is equal to omega squared5In the square.
  • If the parameter is not a number,Math.hypotMethod converts it to a value. Returns any parameter that cannot be converted to a valueNaN.