百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 5个ES10的新特性
分享文章到:

5个ES10的新特性

发布时间:09/01 来源:未知 浏览: 关键词:
本年,ECMAScript 2019(简称ES2019)将会公布。 新功效包罗Object.fromEntries(),trimStart(),trimEnd(),flat(),flatMap(),symbol对象的description属性,可选的catch绑定等。

1、Object.fromEntries()

在JavaScript中,将数据从一种格局转换为另一种格局非常常见。 为了便于将对象转换为数组,ES2017引入了Object.entrie()办法。 此办法将对象作为参数,并以[key,value]的情势返回对象本人的可枚举字符串键控属性对的数组。 例如:

const obj = {one: 1, two: 2, three: 3};

console.log(Object.entries(obj));    
// => [["one", 1], ["two", 2], ["three", 3]]

但是假如我们想要做相反的事情并将键值对列表转换为对象呢? 某些编程说话(如Python)为此供给了dict()函数。 在Underscore.js和Lodash中还有_.fromPairs函数。

ES2019引入Object.fromEntries()办法为JavaScript带来相似的功效, 此静态办法同意你轻松地将键值对列表转换为对象:

const myArray = [['one', 1], ['two', 2], ['three', 3]];
const obj = Object.fromEntries(myArray);

console.log(obj);    // => {one: 1, two: 2, three: 3}

如你所见,Object.fromEntries()与Object.entries()所做的事情恰好相反。 虽然之前可以实现Object.fromEntries()雷同的功效,但它实现方式有些复杂:

const myArray = [['one', 1], ['two', 2], ['three', 3]];
const Array.from(myArray).reduce((acc, [key, val]) 
=> Object.assign(acc, {[key]: val}), {})

console.log(obj);    // => {one: 1, two: 2, three: 3}

请记住,传递给Object.fromEntries()的参数可以是实现可迭代和谈的任何对象,只要它返回一个两元素,相似于数组的对象即可。

例如,在以下代码中,Object.fromEntries() 将Map对象作为参数,并创立一个新对象,其键和对应值由Map中的对给出:

const map = new Map();
map.set('one', 1);
map.set('two', 2);

const obj = Object.fromEntries(map);

console.log(obj);    // => {one: 1, two: 2}

Object.fromEntries() 办法关于转换对象也非常有用,思索以下代码:

const obj = {a: 4, b: 9, c: 16};

// 将对象转换为数组
const arr = Object.entries(obj);

// 运算数字的平方根
const map = arr.map(([key, val]) => [key, Math.sqrt(val)]);

// 将数组转换回对象
const obj2 = Object.fromEntries(map);

console.log(obj2);  // => {a: 2, b: 3, c: 4}

上述代码将对象中的值转换为其平方根。 为此,它第一将对象转换为数组,然后使用map()办法猎取数组中值的平方根,结果是可以转换回对象的数组。

使用Object.fromEntries()的另一种状况是处置URL的查询字符串,如本例所示

const paramsString = 'param1=foo&param2=baz';
const searchParams = new URLSearchParams(paramsString);

Object.fromEntries(searchParams);    // => {param1: "foo", param2: "baz"}

此代码中,查询字符串将传递给 URLSearchParams()结构函数。 然后将返回值(即URLSearchParams对象实例)传递给Object.fromEntries() 办法,结果是一个包括每个参数作为属性的对象。

Object.fromEntries() 办法当前是第4阶段提案,这意味着它已预备好包括在ES2019标准中。

2、trimStart() and trimEnd()

trimStart()和trimEnd()办法在实现与trimLeft()和trimRight()雷同。这些办法当前处于第4阶段,将被增加到标准中,以便与padStart()和padEnd()保持一致,来看一些例子:

const str = "   string   ";

// es2019
console.log(str.trimStart());    // => "string   "
console.log(str.trimEnd());      // => "   string"

// 雷同结果
console.log(str.trimLeft());     // => "string   "
console.log(str.trimRight());    // => "   string"

关于Web兼容性,trimLeft() 和trimRight() 将保存为trimStart() 和trimEnd() 的别号。

3、flat() and flatMap()

flat() 办法可以将多维数组展平成一维数组

const arr = ['a', 'b', ['c', 'd']];
const flattened = arr.flat();

console.log(flattened);    // => ["a", "b", "c", "d"]

之前,我们经常使用reduce()或concat()来展平多维数组:

const arr = ['a', 'b', ['c', 'd']];
const flattend = [].concat.apply([], arr);

// or
// const flattened =  [].concat(...arr);

console.log(flattened);    // => ["a", "b", "c", "d"]

请留意,假如供给的数组中有空值,它们会被抛弃:

const arr = ['a', , , 'b', ['c', 'd']];
const flattened = arr.flat();

console.log(flattened);    // => ["a", "b", "c", "d"]

flat() 还接受一个可选参数,该参数指定嵌套数组应当被展平的级别数。 假如未供给参数,则将使用默许值1:

const arr = [10, [20, [30]]];

console.log(arr.flat());     // => [10, 20, [30]]
console.log(arr.flat(1));    // => [10, 20, [30]]
console.log(arr.flat(2));    // => [10, 20, 30]

flatMap() 办法将map()和flat()组合成一个办法。 它第一使用供给的函数的返回值创立一个新数组,然后连接该数组的所有子数组元素。 来个例子:

const arr = [4.25, 19.99, 25.5];

console.log(arr.map(value => [Math.round(value)]));    
// => [[4], [20], [26]]

console.log(arr.flatMap(value => [Math.round(value)]));    
// => [4, 20, 26]

数组将被展平的深度级别为1.假如要从结果中删除项目,只需返回一个空数组:

const arr = [[7.1], [8.1], [9.1], [10.1], [11.1]];

// do not include items bigger than 9
arr.flatMap(value => {
  if (value >= 10) {
    return [];
  } else {
    return Math.round(value);
  }
});  

// returns:
// => [7, 8, 9]

除了正在处置的当前元素外,回调函数还将接收元素的索引和对数组本身的援用。flat()和flatMap()办法当前处于第4阶段。

4、Symbol 对象的 description 属性

在创立Symbol时,可认为调试目的向其增加description (描写)。有时候,能够直接拜访代码中的description 是很有用的。

ES2019 中为Symbol对象增加了只读属性 description ,该对象返回包括Symbol描写的字符串。

let sym = Symbol('foo');
console.log(sym.description);    // => foo

sym = Symbol();
console.log(sym.description);    // => undefined

// create a global symbol
sym = Symbol.for('bar');
console.log(sym.description);    // => bar

5、可选的 catch

try catch 语句中的catch有时候并没有用,思索下面代码:

try {
  // 使用阅读器大概尚未实现的功效
} catch (unused) {
  // 这里回调函数中已经帮我们处置好的错误
}

此代码中的catch回调的信息并没有用途。 但这样写是为了不SyntaxError错误。 ES2019可以省略catch四周的括号:

try {
  // ...
} catch {
  // ....
}

别的:ES2020 的 String.prototype.matchAll

matchAll() 办法是ES2020 第4阶段提议,它针对正则表达式返回所有匹配(包罗捕捉组)的迭代器对象。

为了与match()办法保持一致,TC39 选中了“matchAll”而不是其他倡议的名称,例如 “matches” 或 Ruby的 “scan”。看个简便的例子:

const re = /(Dr\. )\w+/g;
const str = 'Dr. Smith and Dr. Anderson';
const matches = str.matchAll(re);

for (const match of matches) {
  console.log(match);
}

// logs:
// => ["Dr. Smith", "Dr. ", index: 0, input: "Dr. Smith and Dr. Anderson", groups: undefined]
// => ["Dr. Anderson", "Dr. ", index: 14, input: "Dr. Smith and Dr. Anderson", groups: undefined]

此正则表达式中的捕捉组匹配字符“Dr”,后跟一个点和一个空格。\w+ 匹配任何单词字符一次或屡次。 并且g标记指示引擎在整个字符串中搜索模式。

此前,必需在轮回中使用exec()办法来实现雷同的结果,这不是非常有效:

const re = /(Dr\.) \w+/g;
const str = 'Dr. Smith and Dr. Anderson';
let matches;

while ((matches = re.exec(str)) !== null) {
  console.log(matches);
}

// logs:
// => ["Dr. Smith", "Dr.", index: 0, input: "Dr. Smith and Dr. Anderson", groups: undefined]
// => ["Dr. Anderson", "Dr.", index: 14, input: "Dr. Smith and Dr. Anderson", groups: undefined]

重要的是要留意尽管match() 办法可以与全局标记g一起使用来拜访所有匹配,但它不供给匹配的捕捉组或索引位置。 比力以下代码:

const re = /page (\d+)/g;
const str = 'page 2 and page 10';

console.log(str.match(re));    
// => ["page 2", "page 10"]

console.log(...str.matchAll(re)); 
// => ["page 2", "2", index: 0, input: "page 2 and page 10", groups: undefined] 
// => ["page 10", "10", index: 11, input: "page 2 and page 10", groups: undefined]

总结

在这篇文章中,我们细心研讨了 ES2019 中引入的几个关键特性,包罗Object.fromEntries(),trimStart(), trimEnd(), flat(), flatMap(),symbol 对象的description 属性乃至可选的catch 。

更多相关知识请关注JavaScript视频教程栏目

以上就是5个ES10的新特性的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有152人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板