Array#{flat,flatMap}

ECMAScript 2019 adds two methods to Array.prototype :flat() and flatMap().

These two methods make it easy to flatten arrays. In the absence of these two methods, flattening an array requires either iteration or recursion

// Hand-written implementation
/* Each element in an array is like a child node. Non-array elements are leaf nodes. Therefore, the input array in this example is a tree of height 2 with seven leaves. Flattening this array is essentially a sequential walk through the leaves. First argument: source array second argument: specifies the level of leveling to nest third argument: new array */

function flatten(sourceArray, depth, flattenedArray = []) {
  for (const element of sourceArray) {
    if (Array.isArray(element) && depth > 0) {
      flatten(element, depth - 1, flattenedArray);
    } else{ flattenedArray.push(element); }}return flattenedArray;
}

const arr = [[0].1.2[3[4.5]], 6];

console.log(flatten(arr, 1));

// [0, 1, 2, 3, [4, 5], 6]
Copy the code

The members of an Array are sometimes arrays, and array.prototype.flat () is used to “flaten” a nested Array into a one-dimensional Array. This method returns a new array with no effect on the original data.

const arr1 = [0.1.2[3.4]].console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0.1.2[[[3.4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
Copy the code

FlatMap () can only expand one level of an array.

// Equivalent to [[[2]], [[4]], [[6]], [[8]].flat()
[1.2.3.4].flatMap((x) = > [[x * 2]]);
// [[2], [4], [6], [8]
Copy the code

Typical scenario: Split an array of several sentences into a new array of individual words

let arr1 = ["it's Sunny in".""."California"];

arr1.map((x) = > x.split(""));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap((x) = > x.split(""));
// ["it's","Sunny","in", "", "California"]
Copy the code

Refer to ES Introduction – Flat for details

Object.fromEntries

Background: The front end uses a Map structure to store data, but when calling the backend API you need to pass a normal Object, you can use object.fromentries () to transform

Object.fromentries is the opposite of object.entries () and is used to convert an array of key-value pairs into objects.

Object.fromEntries([
  ["foo"."bar"],
  ["baz".42]]);// { foo: "bar", baz: 42 }
Copy the code

The main purpose of this method is to restore the data structure of the key-value pair to an object, so it is particularly suitable for converting Map structures to objects.

Usage scenario:

The Map key-value pair structure is converted to an object

/ / a
const entries = new Map([["foo"."bar"],
  ["baz".42]]);Object.fromEntries(entries);
// { foo: "bar", baz: 42 }

/ / two cases
const map = new Map().set("foo".true).set("bar".false);
Object.fromEntries(map);
// { foo: true, bar: false }
Copy the code

Array to Object

const arr = [
  ["0"."a"],
  ["1"."b"],
  ["2"."c"]];const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
Copy the code

Browser query parameters are converted to objects

let query = Object.fromEntries(new URLSearchParams("foo=bar&baz=qux"));
// {foo: "bar", baz: "qux"}
console.log(query);
Copy the code

Regroup the values of an object

let arr = [
  { name: "Alice".age: 40 },
  { name: "Bob".age: 36},];let obj = Object.fromEntries(arr.map(({ name, age }) = > [name, age]));
// {Alice: 40, Bob: 36}
console.log(obj);
Copy the code

String#{trimStart,trimEnd}

ES2019 adds trimStart() and trimEnd() methods to string instances. Their behavior is consistent with trim(),

  • trimStart()Eliminate Spaces in the header of the string,
  • trimEnd()Eliminate trailing whitespace.

They all return the new string, not the original string.

const s = " abc ";

s.trim(); // "abc"
s.trimStart(); // "abc "
s.trimEnd(); // " abc"
Copy the code

Symbol#description

When creating a Symbol, you can add a description.

const sym = Symbol("foo");
Copy the code

In the above code, the description of sym is the string foo.

However, reading this description requires that Symbol be explicitly converted to a string, as follows.

const sym = Symbol("foo");

String(sym); // "Symbol(foo)"
sym.toString(); // "Symbol(foo)"
Copy the code

The above usage is not very convenient. ES2019 provides an instance attribute, description, that directly returns a description of the Symbol.

const sym = Symbol("foo");

sym.description; // "foo"
Copy the code

ES2019 provides an instance attribute, description, that directly returns a description of the Symbol.

// When creating a Symbol, you can add a description.
const sym = Symbol("foo");

sym.description; // "foo"
Copy the code

In the above code, the description of sym is the string foo.

try { } catch {} // optional binding

Older versions of try/catch statements require a variable for the catch clause. We can leave it out now

/ / the old version
try {
  console.log(a);
} catch (error) {
  console.log("There was an error.");
}

// ES2019-SE10

// If we don't care about the error message and just want to know if an error is reported, we can ignore the catch parameter
try {
  console.log(a);
  return true;
} catch {
  console.log("There was an error.");
  return false;
}
Copy the code

U + 2028 and U + 2029

In versions prior to ES2019, unescaped is not accepted

  • Line separatorsU + 2028
  • Paragraph separatorU + 2029

ES2019 allows JavaScript strings to be typed directly with U+2028 (line separator) and U+2029 (segment separator).

/* before ES2019, the following code will not report an error. * /
const PS = eval("'\u2029'");
Copy the code

ES Entry -U+2028 and U+2029

JSON – stringify – transformation

To ensure that a valid UTF-8 character is returned, ES2019 changes the behavior of json.stringify (). If a single code point between 0xD800 and 0xDFFF is encountered, or if a pair form does not exist, it returns an escape string, leaving the application to decide what to do next.

JSON.stringify("\u{D834}"); // ""\\uD834""
JSON.stringify("\uDF06\uD834"); // ""\\udf06\\ud834""
Copy the code

ES Getting Started – json-stringify – transformation

Array.prototype.sort() stable sort

Earlier ECMAScript did not specify whether the default sorting algorithm for array.prototype.sort () was stable or not, leaving it up to the browser to decide, which resulted in some implementations being unstable. ES2019 specifies that the default sorting algorithm for array.prototype.sort () must be stable. This has been done, and the default sorting algorithms of all major implementations of JavaScript are now stable.

const arr = ["peach"."straw"."apple"."spork"];

const stableSorting = (s1, s2) = > {
  if (s1[0] < s2[0]) return -1;
  return 1;
};

arr.sort(stableSorting);
// ["apple", "peach", "straw", "spork"]
Copy the code

ES Introduction – Sort stability

revised Function#toString

ES2019 makes changes to the toString() method for function instances.

The toString() method returns the function code itself, previously omitting comments and whitespace.

function/ *foo comment* /foo() {}

/ / the old version
foo.toString();
// function foo() {}

/ / the new
foo.toString();
// "function /* foo comment */ foo () {}"
Copy the code

The last

The article is shallow and humble, welcome everyone to see the comment area to leave your opinion!

Feel the harvest of students welcome to like, follow a wave!

The articles

  • The most complete ECMAScript guide
  • ECMAScript ES2015-ES6
  • ECMAScript ES2016-ES7
  • ECMAScript ES2017-ES8
  • ECMAScript ES2018-ES9
  • ECMAScript ES2019-ES10
  • ECMAScript ES2021-ES11
  • ECMAScript ES2020-ES12
  • ECMAScript ES2022-ES13