brief introduction

ES10 yes ECMA The association is in 2019 year 6 A version of this month , the reason being that ECMAScript The tenth version of , So it's also called ES10.

Let's talk about ES10 New features .

ES10 Introduced 2 Big features and 4 A small feature , Let's talk about it one by one .

Array New method of flat and flatMap

stay ES10 in , to Array Two new methods have been introduced , Namely flat and flatMap.

Let's take a look first flat.

Let's see Array.prototype.flat() The definition of :

.flat(depth = 1): any[]

flat The role of the Array Medium Array Take out the contents of , Put it on top Array in . We can pass in a depth Parameters , It means the need for flat Of Array Hierarchy .

for instance :

> [ 1,2, [3,4], [[5,6]] ].flat(0) // no change
[ 1, 2, [ 3, 4 ], [ [ 5, 6 ] ] ] > [ 1,2, [3,4], [[5,6]] ].flat(1)
[ 1, 2, 3, 4, [ 5, 6 ] ] > [ 1,2, [3,4], [[5,6]] ].flat(2)
[ 1, 2, 3, 4, 5, 6 ]

When depth=0 When , It means it won't be right Array Built in Array Conduct flat operation .

Let's see Array.prototype.flatMap() The definition of :

 .flatMap<U>(
callback: (value: T, index: number, array: T[]) => U|Array<U>,
thisValue?: any
): U[]

flatMap yes map and flat The combination of , The following two operations are equivalent :

arr.flatMap(func)
arr.map(func).flat(1)

Let's see a few flatMap Example :

> ['a', 'b', 'c'].flatMap(x => x)
[ 'a', 'b', 'c' ]
> ['a', 'b', 'c'].flatMap(x => [x])
[ 'a', 'b', 'c' ]
> ['a', 'b', 'c'].flatMap(x => [[x]])
[ [ 'a' ], [ 'b' ], [ 'c' ] ] > ['a', 'b', 'c'].flatMap((x, i) => new Array(i+1).fill(x))
[ 'a', 'b', 'b', 'c', 'c', 'c' ]

Object New method of fromEntries

Object.fromEntries The main function of the system is through the given [key,value], To create a new Object object .

var newObj =  Object.fromEntries([['foo',1], ['bar',2]]);
console.log(newObj);
{ foo: 1, bar: 2 }

In the example above , Let's go through two given key-value Yes , Created a new object object .

and fromEntries The opposite way , Namely Object.entries, Used to traverse object properties .

It's just an example , Let's call it again Object.entries Method :

console.log(Object.entries(newObj));
[ [ 'foo', 1 ], [ 'bar', 2 ] ]

String New method of trimStart and trimEnd

JS There is already trim Methods , Can eliminate String Space before and after .

> '  abc  '.trim()
'abc'

But sometimes it may be necessary to eliminate the spaces before or after ,ES10 Introduced trimStart and trimEnd Method :

> '  abc  '.trimStart()
'abc '
> ' abc '.trimEnd()
' abc'

Be careful , Some browsers may already have trimLeft and trimRight Method , stay EMCAScript Specification , They and trimStart,trimEnd It is equivalent. .

addressable Symbol Of description attribute

We're creating Symbol When , You can pass in a description As a parameter to build Symbol:

const sym = Symbol('www.flydean.com');

stay ES10 Before , We want to visit Symbol Of description Here's how it works :

console.log(String(sym));
//Symbol(www.flydean.com)

Now we can go straight through description Property to access :

console.log(sym.description);
//www.flydean.com

Negligible catch Parameters

In the traditional way of writing ,catch It's about accepting a error Parametric :

try {
// ···
} catch (error) {
// ···
}

But sometimes we already know that this anomaly is unimportant , Or say , We want to ignore this anomaly , So in ES10 in , We can omit this error Parameters :

try {
// ···
} catch {
// ···
}

Array The stable ordering of data

Array There is one sort function , You can sort by element content .

ES10 The concept of stable sorting is introduced in , That is to say, if it's sorted key It's the same , So these are the same key There is no change in the order of .

for instance :

const arr = [
{ key: 'b', value: 1 },
{ key: 'a', value: 2 },
{ key: 'b', value: 3 },
];
arr.sort((x, y) => x.key.localeCompare(y.key, 'en-US'));

We according to the key To sort , So that a, be ranked at b front , But the two one. key=b The position of the elements in the matrix will not change .

console.log(arr);
[
{ key: 'a', value: 2 },
{ key: 'b', value: 1 },
{ key: 'b', value: 3 }
]

JSON.stringify

JSON It's a very convenient data transfer format , It is not like XML So complicated , The advantage is small size , Easy to transmit .

according to RFC3629 The specification of , Transmit... In a public environment JSON, You have to use UTF-8 Encoding .

JSON text exchanged between systems that are not part of a closed

ecosystem MUST be encoded using UTF-8 [RFC3629].

Talking about JSON.stringify Before , So let's go back ES6 Medium Escape sequences.

ES6 There are three escape:

  1. Hex escape:16 Base number escape. What's more 2 Bit 16 Base number .
  > '\x7A' === 'z'
true
  1. Unicode escape: What's more 4 Bit 16 Base number
 > '\u007A' === 'z'
true
  1. Unicode code point escape: What's more 1 One or more 16 Base number
  > '\u{7A}' === 'z'
true

The last escape is in ES6 Introduced in .

unicode The character set is finally stored in a file or memory , Direct storage , Too much space . How can I save it ? Use fixed 1 Bytes ,2 A byte or a variable length byte ? So according to the different coding methods , Divided into UTF-8,UTF-16,UTF-32 And so on .

among UTF-8 It's a variable length encoding scheme , It USES 1-4 Bytes to store .UTF-16 Use 2 A or 4 Bytes to store .

and UTF-32 It's using 4 Bytes to store . Of the three coding methods , Only UTF-8 Is compatible ASCII Of , That's why internationally UTF-8 The reason why coding is more common ( After all, computer technology is made by Westerners ).

We know that Unicode In the encoding ,U+D800 To U+DFFF These characters are reserved for UTF-16 Use , If we input characters in this range , It can't be converted into UTF-8 Format .

This is the original JSON.stringify Possible problems .

stay ES10 in ,JSON.stringify For those that cannot be converted to UTF-8 The characters of , Return the corresponding code unit escape sequences.

console.log(JSON.stringify('\u{D800}'));
"\ud800"

JSON Be classified as ECMAScript Subset

Before ,JSON No ECMAScript Subset , As a result, some of them can be JSON Characters contained in , Can't be in ECMAScript In the literal quantity of , such as U+2028 and U+2029 :

const sourceCode = '"\u2028"';
eval(sourceCode); // SyntaxError JSON.parse(json); // OK

After this change , We don't need to distinguish between them when we code JSON still ECMAScript 了 .

Function Of toString Method

stay ES10 in , If Function It can be done by ECMAScript The way the source code is expressed , be toString Will return the code of this function directly :

> class C { foo() { /*hello*/ } }
> C.prototype.foo.toString()
'foo() { /*hello*/ }'

If it's some native Methods , Like the bottom floor c perhaps c++ Implemented code , Then return directly [native code]:

> Math.pow.toString()
'function pow() { [native code] }'

The author of this article :flydean Program those things

Link to this article :http://www.flydean.com/ecmascript-10/

In this paper, the source :flydean The blog of

Welcome to my official account. :「 Program those things 」 The most popular interpretation , The deepest dry goods , The most concise tutorial , There are so many tricks you don't know about waiting for you to discover !

ECMAScript 2019(ES10) More articles about new features

  1. javaScript ES7 ES8 ES9 ES10 New characteristics

    reference : https://tuobaye.com/2018/11/27/%E7%BB%86%E8%A7%A3JavaScript-ES7-ES8-ES9-%E6%96%B0%E7%89%B9%E6% ...

  2. ES6 Introduction to new features

    ES6 Introduction to new features Environmental installation npm install -g babel npm install -g babel-node // Offer based on node Of REPL Environmental Science // establish .babelrc file {&qu ...

  3. ECMAScript 6 Introduction to new features

    Catalog brief introduction ECMAScript and JavaScript The relationship between let and const Deconstruct assignment Extension of arrays Function extension brief introduction ECMAScript 6.0( hereinafter referred to as ES6) yes JavaScript Language ...

  4. PHP7 New characteristics brief introduction

    Sort out some common new features , Welcome to thumb up !!! New operator 1.?? $username = $_GET['user'] ?? ''; $username = isset($_GET['user']) ? $ ...

  5. webpack3 Introduction to new features

    6 month 20 Number webpack Launched 3.0 edition , The government also issued an announcement . According to the announcement ,webpack The team will focus on the functional requirements proposed by the community , It's going to be fast at the same time . Stable release rhythm . This article is mainly based on the contents of the announcement , Brief introduction ...

  6. Java8 Introduction to new features

    Java8 yes 2014 Published in , It has been nearly three years now , Although I have studied before , But the study is scattered , No system , And it doesn't cover Java8 All the features . Because the company has used JDK1.8, So you can use Java ...

  7. java8 New characteristics —— brief introduction

    java8 It's been around for a long time , But it wasn't used in previous projects , So it's always just a little bit , I just changed a new company recently , In development, we need to use java8 To develop , So I'll come to learn it right away java8 Get new features . One . New characteristics ...

  8. java8 New characteristics - brief introduction

    One . primary coverage : The most important one is lambda expression And Stream API lambda expression Functional interface Method references and constructor references Stream API Default and static methods in interfaces New time date API ...

  9. Java Efficient development IntelliJ IDEA 2019.1 New characteristics

    1. Refactoring class . file . Symbol ,Action Search for IntelliJ IDEA( hereinafter referred to as IDEA) Search in can be divided into the following categories Class search , such as Java,Groovy,Scala Equivalent documents File search , Class document ...

  10. iOS13 Introduction to new features

    Catalog One .Dark Mode Dark Mode Two .Status Bar to update 3、 ... and .UIActivityIndicatorView Load view Four . summary One .Dark Mode Dark Mode 1.1 iOS13 Launched D ...

Random recommendation

  1. Jpush Push module

      This article was published on 14:17:10 2015/3/24 Republish to Whale song Jpush Push module     Or above . SDK Integration steps . Import SDK Develop packages into your own application projects •     decompression ...

  2. Python Learning notes 5- Tuples

    Tuples are enclosed in parentheses , The elements are separated by commas >>> t = 123,'abc',["come","here"] >>> ...

  3. BZOJ2708 [Violet 1] Puppets

    The first thing to think about is greed ... It must be wrong ...T T And then it turns out that it can DP Of ... But we have to sort it first Make f[i] Before presentation i The worst way to lose a puppet is to lose a few , be f[i] = max(f[j] + calc(j + 1, i ...

  4. usb Protocol analysis - Device descriptor configuration package - The descriptor

    /* usb Protocol analysis is for your reference only --- Device descriptor configuration package , Device descriptor , Address settings , Configuration descriptor , String descriptor */ /* -1- usb Device descriptor configuration package */ typedef struct _USB_ ...

  5. Linux Check the file size

    1. View the current file size du -sh ./ du [-abcDhHklmsSx] [-L < Symbolic connection >][-X < file >][--block-size][--exclude=< ...

  6. Cannot create a session after the response has been committed

    Sometimes in operation Session when , The system will throw the following exception java.lang.IllegalStateException: Cannot create a session after the response ...

  7. Git Step by Step – (6) Git Remote warehouse

    All of the things that appeared in the previous article Git The operation is based on the local warehouse , But in daily work, many people need to cooperate , It's impossible to work in your own code repository all the time . therefore , Let's start with Git Remote warehouse . stay Git In the system , The user can go through push/pull ...

  8. 【 database 】MFC ODBC( Two )

    3、 ... and .CRecordset class 1.IsBOF And IsEOF (1)IsBOF If the recordset has no records , Or has moved forward before the first record , Then it returns nonzero : Otherwise return to 0. The details are as follows : 1) visit Open After the function , If the record ...

  9. [CC-MCHEF]MasterChef

    [CC-MCHEF]MasterChef The main idea of the topic : \(n(n\le10^5)\) Flower piece , The first \(i\) The beauty of the flower is \(b_i(|b_i|\le10^9)\). The overall beauty is the sum of the beauty of each flower . Because of ...

  10. Java Multithreading starts repeatedly in

    In the interview, I am often asked questions about multithreading : Today, I found that the following code will throw an exception during the test : java.lang.IllegalThreadStateException public static void m ...