这些 JS 的新语法有点东西啊

开发 前端
这是个挺不错的新语法。其他有些语言是可以用 arr[-1] 来获取数组末尾的元素,但是对于 JS 来说这是实现不了的事情。因为 [key] 对于对象来说就是在获取 key 对应的值。

 [[420374]]

TC39 的提案笔者一直有关注,攒了一些有趣的今天来聊聊。

PS:提案总共五个阶段,只有到阶段 4 才会被纳入到发布规范中,其它的只是有几率会被纳入。

.at()

这是个挺不错的新语法。其他有些语言是可以用 arr[-1] 来获取数组末尾的元素,但是对于 JS 来说这是实现不了的事情。因为 [key] 对于对象来说就是在获取 key 对应的值。数组也是对象,对于数组使用 arr[-1] 就是在获取 key 为 -1 的值。

由于以上原因,我们想获取末尾元素就得这样写 arr[arr.length - 1],以后有了 at 这个方法,我们就可以通过 arr.at(-1) 来拿末尾的元素了,另外同样适用类数组、字符串。 

  1. // Polyfill  
  2. function at(n) {  
  3.     // ToInteger() abstract op  
  4.     n = Math.trunc(n) || 0;  
  5.     // Allow negative indexing from the end  
  6.     if(n < 0) n += this.length;  
  7.     // OOB access is guaranteed to return undefined  
  8.     if(n < 0 || n >= this.length) return undefined;  
  9.     // Otherwise, this is just normal property access  
  10.     return this[n];  

顶层 await

await 都得用 async 函数包裹大家肯定都知道,这个限制导致我们不能在全局作用域下直接使用 await,必须得包装一下。

有了这个提案以后,大家就可以直接在顶层写 await 了,算是一个便利性的提案。

目前该提案已经进入阶段 4,板上钉钉会发布。另外其实 Chrome 近期的更新已经支持了该功能。

image-20210620162451146

Error Cause

这个语法主要帮助我们便捷地传递 Error。一旦可能出错的地方一多,我们实际就不清楚错误到底是哪里产生的。如果希望外部清楚的知道上下文信息的话,我们需要封装以下 error。 

  1. async function getSolution() {  
  2.   const rawResource = await fetch('//domain/resource-a')  
  3.     .catch(err => {  
  4.       // How to wrap the error properly?  
  5.       // 1. throw new Error('Download raw resource failed: ' + err.message); 
  6.       // 2. const wrapErr = new Error('Download raw resource failed');  
  7.       //    wrapErr.cause = err
  8.       //    throw wrapErr;  
  9.       // 3. class CustomError extends Error {  
  10.       //      constructor(msg, cause) {  
  11.       //        super(msg);  
  12.       //        this.cause = cause;  
  13.       //      } 
  14.       //    }  
  15.       //    throw new CustomError('Download raw resource failed', err);  
  16.     }) 
  17.    const jobResult = doComputationalHeavyJob(rawResource);  
  18.   await fetch('//domain/upload', { method: 'POST', body: jobResult });  
  19. await doJob(); // => TypeError: Failed to fetch 

那么有了这个语法以后,我们可以这样来简化代码: 

  1. async function doJob() {  
  2.   const rawResource = await fetch('//domain/resource-a')  
  3.     .catch(err => {  
  4.       throw new Error('Download raw resource failed', { cause: err });  
  5.     }); 
  6.   const jobResult = doComputationalHeavyJob(rawResource);  
  7.   await fetch('//domain/upload', { method: 'POST', body: jobResult })  
  8.     .catch(err => {  
  9.       throw new Error('Upload job result failed', { cause: err });  
  10.     });  
  11.  
  12. try {  
  13.   await doJob();  
  14. } catch (e) {  
  15.   console.log(e);  
  16.   console.log('Caused by', e.cause);  
  17.  
  18. // Error: Upload job result failed  
  19. // Caused by TypeError: Failed to fetch 

管道运算符

这个语法的 Star 特别多,有 5k 多个,侧面也能说明是个受欢迎的语法,但是距离发布应该还有好久,毕竟这个提案三四年前就有了,目前还只到阶段 1。

这个语法其实在其他函数式编程语言上很常见,主要是为了函数调用方便: 

  1. let result = exclaim(capitalize(doubleSay("hello")));  
  2. result //=> "Hello, hello!"  
  3. let result = "hello"  
  4.   |> doubleSay  
  5.   |> capitalize  
  6.   |> exclaim;  
  7. result //=> "Hello, hello!" 

这只是对于单个参数的用法,其它的用法有兴趣的读者可以自行阅读提案,其中涉及到了特别多的内容,这大概也是导致推进阶段慢的原因吧。

新的数据结构:Records & Tuples

这个数据结构笔者觉得发布以后会特别有用,总共新增了两种数据结构,我们可以通过 # 来声明:

1. #{ x: 1, y: 2 }2.#[1, 2, 3, 4]

这种数据结构是不可变的,类似 React 中为了做性能优化会引入的 immer 或者 immutable.js,其中的值只接受基本类型或者同是不可变的数据类型。 

  1. const proposal = #{  
  2.   id: 1234,  
  3.   title: "Record & Tuple proposal",  
  4.   contents: `...`,  
  5.   // tuples are primitive types so you can put them in records:  
  6.   keywords: #["ecma", "tc39", "proposal", "record", "tuple"],  
  7. };  
  8. // Accessing keys like you would with objects!  
  9. console.log(proposal.title); // Record & Tuple proposal  
  10. console.log(proposal.keywords[1]); // tc39  
  11. // Spread like objects!  
  12. const proposal2 = #{  
  13.   ...proposal,  
  14.   title: "Stage 2: Record & Tuple",  
  15. };  
  16. console.log(proposal2.title); // Stage 2: Record & Tuple  
  17. console.log(proposal2.keywords[1]); // tc39  
  18. // Object functions work on Records:  
  19. console.log(Object.keys(proposal)); // ["contents", "id", "keywords", "title"] 

最后

以上笔者列举了一部分有意思的 TC39 提案,除了以上这些还有很多提案,各位读者有兴趣的话可以在 TC39 中寻找。 

 

责任编辑:庞桂玉 来源: 前端大全
相关推荐

2020-12-14 05:57:01

clipboard.Selection execCommand

2022-08-19 12:12:02

TypeScriptInfer 类型

2021-10-15 10:26:28

鸿蒙HarmonyOS应用

2010-03-29 10:45:48

HTML 5

2010-09-09 15:32:48

SQL插入数据

2009-07-08 18:07:58

jvm jre

2023-11-06 19:00:17

Python

2021-12-28 08:46:00

Vue3refreactive

2024-03-15 08:45:31

Vue 3setup语法

2021-04-06 21:30:56

代码SPI重构

2012-05-22 01:49:22

Highlight.jJavaWEB

2021-12-05 23:17:18

iOS苹果系统

2021-01-03 09:44:34

解压软件解压神器应用

2019-03-26 09:20:12

苹果 iOS系统

2017-09-26 10:00:15

前端JS语法

2023-01-30 09:01:34

DecoratorsJS语法

2022-05-06 08:26:21

babel编译器

2018-03-22 14:29:16

路由器网速慢

2011-08-24 10:43:35

2022-09-07 09:01:14

JS操作符运算符
点赞
收藏

51CTO技术栈公众号