As we all know, JS is in the position of front-end development. It’s really important to learn it well.

es7

Array.prototype.includes

  • Determines whether the element is contained in the array.
  • Parameter one is the string to query, and parameter two is the subscript to start the search. The default is 0.

The previous method of determining indexOf.

    const names = ["zh"."llm".NaN]

    if (names.indexOf("zh")! = = -1) {
      console.log("Contains the zh element")}Copy the code

Defect cannot determine NaN == NaN. Includes considers NaN == NaN.


if (names.indexOf(NaN)! = = -1) {// false
  console.log("Contains NaN")}if (names.includes(NaN)) { // true
  console.log("Contains NaN")}Copy the code

Exponentiation operator

Prior to ES7, calculating the power of a number was done using the Math.pow method.

In ES7, the ** operator was added to calculate the power of a number.

    const result1 = Math.pow(3.3)
    // ES7: **
    const result2 = 3 ** 3
Copy the code

es8

Object.values

Keys can be used to retrieve all keys of an Object. In ES8, object. values is provided to retrieve all values.

    const obj = {
      name: "zh".age: 22
    }

    console.log(Object.keys(obj)) // [ 'name', 'age' ]
    console.log(Object.values(obj)) // [ 'zh', 22 ]
Copy the code

If an array is passed in, it returns the array itself

    // Use very little
    console.log(Object.values(["zh"."llm"]))
Copy the code

If a string is passed, it returns an array of each character. Equivalent to STR. The split (” “)

    console.log(Object.values("zh"))// [ 'z', 'h' ]
    console.log("zh".split("")) // [ 'z', 'h' ]
Copy the code

Object.entries

Object.entries are used to retrieve an array containing an array of key-value pairs for enumerable properties.

    const obj = {
      name: "zh".age: 22
    }

    console.log(Object.entries(obj)) // [ [ 'name', 'zh' ], [ 'age', 22 ] ]
    const objEntries = Object.entries(obj)
    objEntries.forEach(item= > {
      console.log(item[0], item[1])})Copy the code

If an array or string is passed in, entries of subscripts and elements are returned.

console.log(Object.entries(["zh"."llm"])) //[ [ '0', 'zh' ], [ '1', 'llm' ] ]
console.log(Object.entries("zh")) // [ [ '0', 'z' ], [ '1', 'h' ] ]
Copy the code

String.prototype.padStart / padEnd

In ES8, the padStart and padEnd methods are added to fill the beginning and end of the string, respectively.

  • Parameter 1 the maximum length to fill, parameter 2 the characters to fill. The default is space padding.
    const message = "Hello World"
    const newMessage = message.padStart(15."*").padEnd(20."-")
    console.log(newMessage) // ****Hello World-----
Copy the code
  • If the maximum length of the fill is less than the length of the original string, the original string will be printed.
    const message = "Hello World"
    console.log(message.padStart(1.0)) //Hello World
Copy the code
  • If the sum of the length of the completion string and the original string exceeds the maximum length, the completion string with more than bits is truncated.
    '12'.padStart(10.'YYYY-MM-DD') // "YYYY-MM-12"
    '09-12'.padStart(10.'YYYY-MM-DD') // "YYYY-09-12"
Copy the code

We have a simple application scenario: for example, we need to hide the first digit of id card and bank card:

    const cardNumber = "321324234242342342341312"
    const lastFourCard = cardNumber.slice(-4)
    const finalCard = lastFourCard.padStart(cardNumber.length, "*")
    console.log(finalCard) / / * * * * * * * * * * * * * * * * * * * * 1312
Copy the code

es10

Array.prototype.flat

“Flatten” a nested array into a one-dimensional array. This method returns a new array with no effect on the original array.

  • Parameter indicating how many layers of the array need to be expanded. The default value is 1.
    [1.2[3[4.5]]].flat() // [1, 2, 3, [4, 5]]

    [1.2[3[4.5]]].flat(2) // [1, 2, 3, 4, 5]
Copy the code
  • If you want to convert it to a one-dimensional array no matter how many layers you have nested, you can use thisInfinityKeyword as parameter.
    [1[2[3]]].flat(Infinity) / / [1, 2, 3]
Copy the code
  • If the original array is empty,flat()Method skips the empty space.
    [1.2.4.5].flat() // [1, 2, 4, 5]
Copy the code

Array.prototype.flatMap

It’s a combination of map and flat. This is equivalent to executing map() and then flat() on the array of returned values. This method returns a new array, leaving the original array unchanged.

  • Argument one traverses the function one by one, and argument two binds the inside of the functionthisValue.
  • He can only expand one layer of the array.
    const messages = ["Hello World"."hello zh"]
    const words = messages.flatMap(item= > {
      return item.split("")})console.log(words) //[ 'Hello', 'World', 'hello', 'zh' ]
Copy the code

Object.fromEntries

We can convert an Object to entries through object. entries. If we have an entry, how do we convert it to an Object?

ES10 provides Object.formEntries for conversion.

    const obj = {
      name: "zh".age: 22
    }

    const entries = Object.entries(obj)
    const newObj = Object.fromEntries(entries)
    console.log(newObj) //{ name: 'zh', age: 22 }
Copy the code

So what are the application scenarios for this approach?

Convert the query string to an object.

    const queryString = 'name=zh&age=22'
    const queryParams = new URLSearchParams(queryString) // Return an iterable
    console.log(queryParams) //{ 'name' => 'zh', 'age' => '22' }

    const paramObj = Object.fromEntries(queryParams)
    console.log(paramObj)
Copy the code

String.prototype.trimStart / trimEnd

They behave in the same way as trim(), with trimStart() removing space at the head of the string (invisible whitespace like TAB, newline characters) and trimEnd() removing space at the end of the string (invisible whitespace like TAB, newline characters). They all return a new string and do not modify the original string.

TrimLeft () is an alias for trimStart(), and trimRight() is an alias for trimEnd().

es11

BigInt

In the early days of JavaScript, we couldn’t properly represent large numbers. A value greater than MAX_SAFE_INTEGER may indicate an incorrect value.

    const maxInt = Number.MAX_SAFE_INTEGER
    console.log(maxInt) / / 9007199254740991
    console.log(maxInt + 1) / / 9007199254740992
    console.log(maxInt + 2) // 9007199254740992
Copy the code

In ES11, a new data type, BigInt, was introduced to represent large integers. BitInt is represented by adding n to the numeric value.

    const bigInt = 900719925474099100n
    console.log(bigInt + 10n)
Copy the code

BigInt does not privately convert numbers of type BigInt to numbers of type Number, so we need to manually convert them before the operation.

    const num = 100
    console.log(bigInt + BigInt(num))

    const smallNum = Number(bigInt)
    console.log(smallNum)
Copy the code

??Null-value merge operator

Before es11, we through the | | to operation. But there are problems with it. If one of the front operands is 0, “” etc., the second operand is still assigned.

    const foo = 0
    const bar1 = foo || "default value"
    console.log(bar1) // default value
Copy the code

So then we can use?? I’m going to do it. The second operand is assigned only if the current operand is null.

    const foo = 0
    const bar1 = foo || "default value"
    const bar2 = foo ?? "defualt value"

    console.log(bar1, bar2) // default value 0
Copy the code

? .Optional chain

Check whether the object on the left is null or undefined directly during the chain call. If so, it does not proceed further and returns undefined.

globalThis

Because in the browser, the global object is window. In NodeJS, the global object is global.

Obtaining global objects is standardized in ES11: globalThis. Printing globalThis, whether in a browser or nodeJS, retrieves the corresponding global object.

for.. In standardization

Prior to ES11, although many browsers supported for… In iterates over object types, but is not standardized by ECMA.

In ES11, it is standardized, for… In is used to traverse the key of an object.

es12

FinalizationRegistry

The FinalizationRegistry object lets you request a callback when the object is garbage collected.

FinalizationRegistry provides a way to request a cleanup callback at some point in time when an object registered in the registry is reclaimed. Cleanup callbacks are sometimes called finalizers.

You can register any object you want to clean up the callback by calling the Register method, passing in the object and its value.

    const finalRegistry = new FinalizationRegistry((value) = > {
      console.log("Objects registered in finalRegistry, one of which is destroyed", value)
    })
    
    let obj = { name: "zh" }
    let info = { age: 22 }

    finalRegistry.register(obj, "obj")
    finalRegistry.register(info, "value")

    obj = null
    info = null
Copy the code

When the registered object is destroyed, the constructor passed in by FinalizationRegistry is called.

WeakRefs

If we assign an object to another reference by default, that reference is a strong reference.

If we want a weak reference, we can use WeakRef.

    const finalRegistry = new FinalizationRegistry((value) = > {
      console.log("Objects registered in finalRegistry, one of which is destroyed", value)
    })

    let obj = { name: "why" }
    let info = new WeakRef(obj)

    finalRegistry.register(obj, "obj")
    obj = null

    setTimeout(() = > {
      console.log(info.deref()) //undefined
      console.log(info.deref()?.name) //undefined
      console.log(info.deref() && info.deref().name) //undefined
    }, 10000)
Copy the code

The above code indicates that when the obj object is null, since the info object is a weak reference to obj, the object in the heap will be destroyed when obJ is destroyed. So info is not available. And weakRef gets the properties in the object through weakref.deref (). When an object is destroyed, its value is undefined.

Other important es6-ES12 knowledge will be introduced separately in the later article.