JavaScript:ES2019 中的新功能

作为最流行的编程语言之一,也是Web主要开发语言,JavaScript不断发展,每次迭代都会获得一些新的内在变化。让我们看看ES2019的一些新提议的功能,这些功能很快就可能出现在我们日常编码中:

Array.flat()

您现在可以将嵌套数组按照指定的深度递归展开。默认值为1,如果要全部展开,可以使用Infinity。这个方法不会修改原始数组,但会创建一个新数组:

const arr1 = [1, 2, [3, 4]];
arr1.flat(); // [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(2); // [1, 2, 3, 4, 5, 6]

const arr3 = [1, 2, [3, 4, [5, 6, [7, 8]]]];
arr3.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8]

如果数组中有一个空槽,它将会被删除:

const arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]

Array.flatMap()

一种新方法,它结合了基本的map函数,然后使用新的Array.flat()方法将结果展平为深度1

const arr1 = [1, 2, 3];

arr1.map(x => [x * 4]); // [[4], [8], [12]]
arr1.flatMap(x => [x * 4]); // [4, 8, 12]

另一个更有用的例子:

const sentence = ["This is a", "regular", "sentence"];

sentence.map(x => x.split(" ")); // [["This","is","a"],["regular"],["sentence"]]
sentence.flatMap(x => x.split(" ")); // ["This","is","a","regular", "sentence"]

String.trimStart()和String.trimEnd()

除了从字符串两边删除空格的**String.Trim()**以外,现在还有单独的方法只能从每一边删除空格:

const test = " hello ";

test.trim(); // "hello";
test.trimStart(); // "hello ";
test.trimEnd(); // " hello";

Object.fromEntries

可以将Key-value对列表转换为对象的新方法。我们可以理解为我们已经熟悉的Object.Entries逆向操作。在转换之后,您将留下一个数组,但现在您可以将操纵的数组返回到一个对象中。让我们尝试一个例子,我们想要对所有对象属性的值进行平方:

const obj = { prop1: 2, prop2: 10, prop3: 25 };

let array = Object.entries(obj); // [["prop1", 2], ["prop2", 10], ["prop3", 25]]

让我们用一个简单的映射将新的键值对列表的值平方:

array = array.map(([key, value]) => [key, Math.pow(value, 2)]); // [["prop1", 4], ["prop2", 100], ["prop3", 225]]

我们已经转换了对象值但我们留下了一个数组,这就是Object.fromEntries的用武之地,将数组转换回对象:

const newObj = Object.fromEntries(array); // {prop1: 4, prop2: 100, prop3: 225}

可选的Catch Binding

新建议允许您完全省略catch()参数,因为在很多情况下您不想使用它:

try {
  //...
} catch (er) {
  //handle error with parameter er
}

try {
  //...
} catch {
  //handle error without parameter
}

Symbol.description

您现在可以访问Symbol的description属性,而不是使用toString()方法:

const testSymbol = Symbol("Desc");

testSymbol.description; // "Desc"

Function.toString()

现在,在函数上调用toString()会完全按照定义的方式返回函数,包括空格和注释。之前:

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

foo.toString(); // "function foo() {}"

现在是:

foo.toString(); // "function /* foo comment /* foo() {}"

JSON.parse()

现在,行分隔符 (\u2028) 和段落分隔符 (\u2029) 符号正确解析,而不是导致SyntaxError。

原文地址:https://blog.tildeloop.com/posts/javascript-what%E2%80%99s-new-in-es2019

翻译:https://github.com/quickjs-zh/

余下全文(1/3)
分享这篇文章:

请关注我们:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注