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

  • Common but overlooked methods for ES6 (Destruct assignments and values first)
  • 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)

Function extension

  • ES6- Function extensions

Function defaults

  1. A function can be defined by assigning a default value to the corresponding argument. The default value is used when the function is called if no corresponding value is passed. Setting defaults can also be used with destructuring assignments.
function detanx(x = 1) { ... Function detanx({name, age = 10} = {name: 'detanx', age: 10}) {... } function detanx({name, age = 10} = {name: 'detanx'}) {... } detanx({age: 12}) // undefined 12Copy the code
  • Incomplete deconstruction does not assign a value even if there is a corresponding key in the following object.
  1. If a function has a parameter with a default value in the middle of the number of arguments and the following parameter does not have a default value, the parameter to use the default value can be passed inundefined.
function detanx(x =  null, y = 6) {
  console.log(x, y);
}
detanx(undefined, null); // null null
Copy the code
  1. The default values will changelengthGets the length returned by the function argument.
  • After specifying a default value, the function’slengthProperty that returns the number of arguments for which no default value is specified. That is, after specifying a default value,lengthProperty will be distorted.
(function (a) {}).length // 1
(function (a = 5) {}).length // 0
(function (a, b, c = 5) {}).length // 2
Copy the code
  • The default argument is not the last argument, so the length attribute does not count toward subsequent arguments.
(function (a = 0, b, c) {}).length // 0
(function (a, b = 1, c) {}).length // 1
Copy the code
  • Using extended operators to represent received arguments,lengthfor0.
(function(... args) {}).length // 0Copy the code
  1. Scope changed after setting the default value
  • When a function is declared initialized, the parameters form a separate scope (context).
var x = 1;
function detanx(x, y = x) {
  console.log(y);
}
f(2) // 2

function detanx(x = x, y = x) {
  console.log(x, y);
}
f(undefined,2) //  ReferenceError: Cannot access 'x' before initialization
Copy the code

Function defaults apply

  1. Specifies that an argument must not be omitted; if omitted, an error is thrown.
function throwIfMissing() {
  throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
  return mustBeProvided;
}
foo()
// Error: Missing parameter
Copy the code
  • parametermustBeProvidedThe default value ofthrowIfMissingThe result of a function run (note the function namethrowIfMissingFollowed by a pair of parentheses), which indicates that the default value of the parameter is not executed at definition time, but at runtime. If the parameter is already assigned, the function in the default value will not run.

Strict mode change

  • ES5Initially, the function can be set to strict mode internally.ES2016A minor change was made to specify that functions cannot be explicitly set to strict mode internally if they use default values, deconstructed assignments, or extended operators, otherwise an error will be reported.
Function doSomething(a, b = a) {'use strict'; Const doSomething = function ({a, b}) {'use strict'; }; // error const doSomething = (... a) => { 'use strict'; }; Const obj = {doSomething({a, b}) {'use strict'; }};Copy the code
  • One problem with this restriction is that arguments are always declared before the function body is executed. An error will only be reported if strict mode is used when entering the function body.
  • Ways to circumvent this restriction.
// The first is to set the global strict mode, which is legal. 'use strict'; Function doSomething(a, b = a) {// code} const doSomething = (function () { 'use strict'; return function(value = 42) { return value; }; } ());Copy the code

Arrow function

  • Use caution points
    1. In vivo functionthisObject is the object at which you define it, not the object at which you use it.
    2. Cannot be used as constructors, that is, not usednewCommand, otherwise an error will be thrown.
    3. UnusableargumentsObject that does not exist in the function body. You can use it if you wantrestParameter substitution.
    4. UnusableyieldCommand, so the arrow function cannot be usedGeneratorFunction.
  • Arrow functions can also be nested like normal functions.
  • Simplify code writing, but reduce code readability.
// Const curry = (fn, arr = []) => (... args) => ( arg => arg.length === fn.length ? fn(... arg) : curry(fn, arg) )([...arr, ...args]); let curryTest = curry( (a, b) => a + b ); CurryTest (1, 2) // returns 3Copy the code

Array extension

  • ES6- Array extension

Extended operator

  • application
    1. Receive the number of uncertain parameters
    function add(... values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, 5, 3) // 10Copy the code
    1. alternativeapplymethods
    • We used to do this when a function needed to take an array argumentfn.apply(this, arr).
    // const args = [0, 1, 2]; function f(x, y, z) { // ... } f.apply(null, args); Function f(x, y, z) {//... } f(... args);Copy the code
    1. Copy, merge arrays, and convert strings to arrays
    const a = [1] const b = [2]; // Copy array const c = [...a]; / / [1] / / merge array [c]... a, b,... / / [1, 2, 1] / / convert the string to an array [...] 'detanx' / / / 'd', 'e', 't', 'a', 'n' and 'x']Copy the code
    1. To achieve theIteratorObject of interface
    • Any defined traversal (IteratorInterface object (seeIteratorCan be converted to a real array using the extension operator.
    Number.prototype[Symbol.iterator] = function*() {
      let i = 0;
      let num = this.valueOf();
      while (i < num) {
        yield i++;
      }
    }
    console.log([...5]) // [0, 1, 2, 3, 4]
    Copy the code
    • For example, functionalargumentsObject is an array of classes;querySelectorAllThe method returns aNodeListObject. It’s also an array-like object.
    let nodeList = document.querySelectorAll('div');
    let array = [...nodeList];
    Copy the code

Array.from

  • Array.fromThe function of the extension operator is similar to that of the extension operator in that it can convert an array of classes to an array, but it can also take a second argument that acts like an arraymapMethod to process each element and place the value in the returned array.
From (new Array(100), (x, I) => I);Copy the code

copyWithin()

  • Array instancecopyWithin()Method, inside the current array, copies the member at the specified location to another location (overwriting the original member) and returns the current array. That is, using this method, you modify the current array.
    Array.prototype.copyWithin(target, start = 0, end = this.length)
    Copy the code
    • target(Required) : Replace data from this location. If it is negative, it is the reciprocal.
    • start(Optional) : Reads data from this position. The default value is0. If the value is negative, it is calculated from the end.
    • end(Optional) : Stops reading data before reaching this location, which is equal to the array length by default. If the value is negative, it is calculated from the end.
  • All three arguments should be numeric; if not, they are automatically converted to numeric values.
[1, 2, 3, 4, 5]. CopyWithin (0, 3, 4) // [4, 2, 3, 4, 5] 1 of 4 [1, 2, 3, 4, 5]. CopyWithin (0, 2, 1) / / [4, 2, 3, 4, 5] / / copies the 3 to 0 bit []. CopyWithin. Call ({length: 5, 3: Let i32A = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, CopyWithin. Call (new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5]Copy the code

The find () and findIndex ()

  • Both methods can take two arguments, the first to the callback function (which can take three arguments: the current value, the current location, and the current array), and the second to bind to the callback functionthis. The difference is thatfindWhat is returned without finding isundefined.findIndexReturns the- 1. Both methods can be foundNaN, makes up for the arrayindexOfMethodological deficiencies.
[1, 4, -5, 10].find((n) => n > 10) // undefined [1, 5, 10, 15].findIndex(function(value, index, arr) { return value > 15; }) // -1 // bind this function f(v){return v > this.age; } let person = {name: 'John', age: 20}; [10, 12, 26, 15].find(f, person); // 1 [NaN].findIndex(y => object.is (NaN, y)) // 0Copy the code

fill

  • fillMethod fills an array with the given value.
['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]
Copy the code
  • As the code above shows, the fill method is handy for initializing an empty array. Any existing elements in the array will be erased.

  • The fill method can also accept a second and third parameters that specify where the fill starts and ends.

- ['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
Copy the code
  • The code above says,fillMethods from1Starts at the digit point and populates the original array7And to the2End before digit.

Note that if the type of the population is an object, then the object is assigned to the same memory address, not the deep-copy object.

let arr = new Array(3).fill({name: "Mike"});
arr[0].name = "Ben";
arr
// [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

let arr = new Array(3).fill([]);
arr[0].push(5);
arr
// [[5], [5], [5]]
Copy the code

includes

  • Whether an array contains a given value and a stringincludesThe method is similar. withindexOfIs the difference between theincludesReturns a Boolean value directly,indexOfYou need to check whether the return value is- 1. This is used when we need whether a variable is one of multiple enumerated valuesincludes.
const name = 'detanx'; Const nameArr = ['detanx', 'det', 'tanx'] includes = = 1) {... } => if(nameArr.includes(name)) { ... } / / to determine whether the name detanx tanx, det the if (name = = = 'detanx' | | name = = = 'det' | | name = = = 'tanx') {... } => nameArr.includes(name);Copy the code

An array of space

  • A vacancy in an array is a position in the array where there is no valueundefinedThe value of one position is equal toundefined, is still valuable.) . For instance,ArrayThe constructor returns arrays that are empty.
Array(3) // [, , ,]
Copy the code
  1. forEach(),filter(),reduce(),every()andsome()All jump over the empty space.
/ / the forEach method [, 'a'] forEach ((x, I) = > console. The log (I)); / / 1 / / filter method (' a ', 'b'), a filter (x = > true) / / [' a ', 'b'] / / every method [, 'a']. Every (x = > x = = = 'a') / / true / / reduce method [1, 2]. The reduce (x, y) = > (x + y) / / 3 / / some methods [, 'a']. Some (x = > x! == 'a') // falseCopy the code
  1. map()The void is skipped, but the value is preserved.
// map method [,'a']. Map (x => 1)Copy the code
  1. join()andtoString()Will treat the empty space asundefinedAnd theundefinedandnullWill be processed as an empty string.
/ / join method [, 'a', undefined, null]. Join (' # ') / / "# # #" / / toString method [, 'a', undefined, null]. ToString () / / ", a,,"Copy the code
  1. Array.from(),.,entries(),keys(),values(),find()andfindIndex()Will process the empty space intoundefined.
Array.from(['a',,'b']) // [ "a", undefined, "b" ] [...['a',,'b']] // [ "a", undefined, "b" ] // entries() [...[,'a'].entries()] // [[0,undefined], [1, "a"]] / / keys () [... [, 'a']. Keys ()] / [0, 1] / / values () [... [, 'a'] values ()] / [undefined, "a"] / / the find () [,'a'].find(x => true) // undefined // findIndex() [,'a'].findIndex(x => true) // 0Copy the code
  1. copyWithin(),fill(),for... ofEmpty Spaces are treated as normal array positions.
[, 'a', 'b',,] the copyWithin (2, 0) / / /, "a",, "a"] new Array (3). The fill (' a ') / / [" a ", "a", "a"] let arr = [and]; for (let i of arr) { console.log(1); } // 1 // 1Copy the code
  • The rules for handling empty Spaces are very inconsistent, so it is recommended to avoid them.

Object extension

  • ES6- Object extension
  • ES6- Object new method

Object property enumeration

  • Each property of an object has a description object (Descriptor) to control the behavior of the property.

The description of the Object. GetOwnPropertyDescriptor method can obtain the attribute Object.

let obj = { foo: 123 };
Object.getOwnPropertyDescriptor(obj, 'foo')
//  {
//    value: 123,
//    writable: true,
//    enumerable: true,
//    configurable: true
//  }
Copy the code
  • An enumerable property that describes an object is called “enumerable.” If it is false, it means that some operations ignore the current property.

  • Currently, there are four operations that ignore enumerable as false.

    1. for... inLoop: Only the enumerable properties of the object itself and its inheritance are iterated over.
    2. Object.keys(): returns the key names of all the enumerable properties of the object itself.
    3. JSON.stringify(): Serializes only enumerable properties of the object itself.
    4. Object.assign(): ignoreenumerableforfalseOnly enumerable properties of the object itself are copied.
  • SymbolAttributes of a type can only passgetOwnPropertySymbolsMethod.

Chain judgment operator

  • ES5We determine whether a deep-level object has a certainkeyYou have to go layer by layer, and now we can go through? .To obtain.
/ / es5 / written/error (when a certain key does not exist undefined. The key will be error code) const firstName = message. The body. The user. The firstName; / / the correct writing const firstName = (message && message. The body & message. The body. The user && message. The body. The user. The firstName) | | 'default'; // es6 const firstName = message? .body? .user? .firstName || 'default';Copy the code
  • The chain judgment operator has three uses.
    1. obj? .prop// Object properties
    2. obj? .[expr]// Object properties
    3. func? . (... args)// Call a function or object method
a? .b // equivalent to a == null? undefined : a.b a? .[x] // equivalent to a == null? undefined : a[x] a? .b() // equivalent to a == null? undefined : a.b() a? .() // Equivalent to a == null? undefined : a()Copy the code
  • Pay attention to the point
    1. Short circuit mechanism
    • ? .The operator acts as a short-circuit mechanism that stops executing as long as the condition is not met.
    // If name does not exist, the user? .name?.firstNameCopy the code
    1. deleteThe operator
    delete a? .b // equivalent to a == null? undefined : delete a.bCopy the code
    • In the code above, ifaisundefinedornull, will return directlyundefined, and will not proceeddeleteOperation.
    1. Influence of parentheses
    • If the attribute chain has parentheses, the chain judgment operator has no effect outside the parentheses, only inside the parentheses.
    (a? .b).c // equivalent to (a == null? undefined : a.b).cCopy the code
    1. An error situation
    • The following syntax is forbidden and an error may be reported.
    // constructor new a? .() new a? .b() // There is template string a to the right of the chain judgment operator. .`{b}` a? .b '{c}' // The chain judgment operator on the left is super super? .() super? The.foo // chain operator is used to assign to the left of the operator a? .b = cCopy the code
    1. The value on the right cannot be decimal
    • To ensure compatibility with previous code, allowfoo? The 3-0Be parsed intofoo ? . 3:0Therefore, if? .Followed by a decimal number, then? .Instead of being treated as a complete operator, it is treated as a ternary operator, that is, the decimal point is assigned to the following decimal number, forming a decimal number.

NullOperational judge??

  • When reading an object property, if the value of a property isnullorundefined, sometimes you need to specify default values for them. The common approach is through||The operator specifies the default value.
  • ||Operator when the left side is an empty string orfalseIs also set to the default value,??Operator only if the left-hand side isnullorundefinedDefault values are set.
/ / | | operation const a = ' '; b = a || 1; console.log(b) // 1 // ?? Operation b = a?? 1; console.log(b) // ''Copy the code
  • ??There is an arithmetic priority problem, which is related to&&and||You must use parentheses to indicate the priority of. Otherwise, an error will be reported.

Object.is()

  • Used to compare whether two values are strictly equal, as opposed to the strict comparison operator (= = =) are basically the same.
Object.is('foo', 'foo')
// true
Object.is({}, {})
// false
Copy the code
  • There are only two differences: one is+ 0Is not equal to0And the other isNaNIs equal to itself.
+0 === -0 //true
NaN === NaN // false

Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
Copy the code

Object.assign

  • For merging objects, the source object (source), all its own properties (no copy of inherited properties), its ownSymbolValue properties and enumerable properties (of propertiesenumerablefortrue), copy to the target object (target). The first argument is the target object, followed by the source object.
const target = { a: 1, b: 1 }; const source1 = { b: 2, c: 2 }; const source2 = { c: 3 }; Object.assign(target, source1, source2); The target / / {2, a: 1, b: c: 3} / / copy Symbol value attribute Object. The assign ({a: 'b'}, {[Symbol (' c ')] : 'd'}) / / {a: 'b', Symbol (c) : 'd'}Copy the code
  • The incomingnullandundefinedComplains.
Object.assign(undefined) // An error was reported object. assign(null) // An error was reportedCopy the code
  • Pay attention to the point
    1. Object.assignMethod implements shallow copy, not deep copy.
    2. When you encounter a property with the same name,Object.assignIs handled by substitution, not by addition.
    3. Array handling
      • Object.assignIt can be used to work with arrays, but it willThink of arrays as objects.
      Object.assign([1, 2, 3], [4, 5])
      // [4, 5, 3]
      Copy the code
    4. The processing of the value function
    • Object.assignOnly values can be copied. If the value to be copied is a value function, it is evaluated and copied.
    const source = {
      get foo() { return 1 }
    };
    const target = {};
    Object.assign(target, source)
    // { foo: 1 }
    Copy the code

Object.keys(), object.values (), object.entries ()

  1. Object.keys()
  • ES5The introduction of theObject.keysMethod that returns an array of all traversable elements of the argument object itself (not inherited).enumerableKey name of the) property. We can use this if we just need the key name of the object.
let obj = { a: 1, b: 2, c: 3 };

for (let key of Object.keys(obj)) {
    console.log(key); // 'a', 'b', 'c'
    console.log(obj[key]) // 1, 2, 3
}
Copy the code
  1. Object.values()
  • withObject.keysMethod, the difference is one return key and one return value. There is no way to get the key name through this method.
let obj = { a: 1, b: 2, c: 3 }; for (let value of Object.values(obj)) { console.log(value); / / 1, 2, 3} / / numerical keys const obj = {100: 'a', 2: 'b', 7: 'c'}; Object.values(obj) // ["b", "c", "a"]Copy the code
  • The property named value is traversed in ascending order of value, so the order returned isb,c,a.
  • Object.valuesThe attribute name is filteredSymbolValue.
  1. Object.entries()
  • Object.entries()The method returns a number that behaves the same way, except that the value type is differentObject.valuesBasically the same.
for (let [key, value] of Object.entries(obj)) {
    console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}
Copy the code
  • I now use the following notation for traversal objects
Object.entries(obj).forEach(([key, value]) => {
    console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
})
Copy the code

Object.fromEntries()

  • Object.fromEntries()Method isObject.entries()To convert an array of key-value pairs into an object. The primary purpose is to restore the key-value pair’s data structure to an object.
Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }
Copy the code
  • MapStructure is just an array of key-value pairs, so it’s good forMapStructure to object.
/ / case a const entries = new Map ([[' foo ', 'bar'], [' baz ', 42]]). Object.fromentries (entries) // {foo: "bar", baz: 42} const map = new map ().set('foo', true).set('bar', false); Object.fromEntries(map) // { foo: true, bar: false }Copy the code