ECMAScript(简称 ES)是 JavaScript 的标准。ES 标准每年更新一次,每个新版本都有一些新特性。本文将介绍 ECMAScript 2019 的新特性。
Array.prototype.{flat, flatMap}
Array.prototype.flat
方法用于将嵌套的数组扁平化。例如,将 [1, [2, 3], [4, [5, 6]]]
扁平化为 [1, 2, 3, 4, 5, 6]
。
----- --- - --- --- --- --- --- ----- ------------------------ -- --- -- -- -- -- --
Array.prototype.flatMap
方法在扁平化数组的同时对每个元素执行一个函数,然后将函数返回的结果组成新的数组。例如,将 [1, 2, 3]
通过 x => [x, x * 2]
映射为 [1, 2, 2, 4, 3, 6]
,再将其扁平化为 [1, 2, 2, 4, 3, 6]
。
----- --- - --- -- --- ------------------------- -- --- - - ----- -- --- -- -- -- -- --
Object.fromEntries
Object.fromEntries
方法将一个键值对数组转换为一个对象。例如,将 [['a', 1], ['b', 2]]
转换为 {a: 1, b: 2}
。
----- ------- - ------ --- ----- ---- ----------------------------------------- -- --- -- -- --
Object.fromEntries
方法可以用于将 Map
转换为对象。
String.prototype.{trimStart, trimEnd}
String.prototype.trimStart
方法去掉字符串开头的空格。例如,将 ' hello '
转换为 'hello '
。
----- --- - - ----- -- ----------------------------- -- ------ -
String.prototype.trimEnd
方法去掉字符串结尾的空格。例如,将 ' hello '
转换为 ' hello'
。
----- --- - - ----- -- --------------------------- -- - ------
Symbol.prototype.description
Symbol.prototype.description
属性返回 Symbol
的描述字符串。例如,将 Symbol('foo')
返回的描述字符串 'foo'
。
----- --- - -------------- ----------------------------- -- -----
总结
ECMAScript 2019 的新特性使 JavaScript 更加强大和方便,但不适合所有编码场景。在编写代码时,需要权衡使用新特性的利弊,以及它们对代码可读性和可维护性的影响。
来源:JavaScript中文网 ,转载请联系管理员! 本文地址:https://www.javascriptcn.com/post/6482e83e48841e98942454ee