Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js新特性 #27

Open
shangguanhonglei opened this issue May 3, 2021 · 0 comments
Open

js新特性 #27

shangguanhonglei opened this issue May 3, 2021 · 0 comments

Comments

@shangguanhonglei
Copy link
Owner

shangguanhonglei commented May 3, 2021

  • 快速幂运算
Math.pow(2,n) //正常幂运算
2 << (n-1) // 利用位左移运算符 <<
2 ** n // 使用**进行幂运算

Math.pow(2,4) = 16
2 << (4-1) = 16
2 ** 4 = 16
  • 顶层对象: globalThis ES2020新特性

JS 中存在一个顶层对象,但是,顶层对象在各种实现里是不统一的。
从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过 window、self 取到全局对象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它们都无法获取,必须使用 global。

var getGlobal = function () {
    if (typeof self !== 'undefined') { return self; }
    if (typeof window !== 'undefined') { return window; }
    if (typeof global !== 'undefined') { return global; }
    throw new Error('unable to locate global object');
};

ES2020 中引入 globalThis 作为顶层对象,在任何环境下,都可以简单的通过 globalThis 拿到顶层对象。

  • 空值合并运算符 ES2020新特性

ES2020 新增了一个运算符 ??。当左侧的操作数为 null 或者 undefined时,返回其右侧操作数,否则返回左侧操作数。
在之前我们经常会使用 || 操作符,但是使用 || 操作符,当左侧的操作数为 0 、 null、 undefined、 NaN、 false、 '' 时,都会使用右侧的操作数。如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。
?? 操作符可以规避以上问题,它只有在左操作数是 null 或者是 undefined 时,才会返回右侧操作数。

const someValue = 0;
const defaultValue = 100;
let value = someValue ?? defaultValue; // someValue 为 0 ,value 的值是 0
  • 可选链操作符

可选链操作符 ?. 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish, 即 null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。

//例如,我们要访问 info 对象的 animal 的 reptile 的 tortoise。但是我们不确定 animal, reptile 是否存在,因此我们需要这样写:
const tortoise = info.animal && info.animal.reptile && info.animal.reptile.tortoise;
//因为 null.reptile 或  undefined.reptile 会抛出错误:TypeError: Cannot read property 'reptile' of undefined 或 TypeError: Cannot read property 'reptile' of null,为了避免报错,如果我们需要访问的属性更深,那么这个这句代码会越来越长。
//使用?.
const tortoise = info.animal?.reptile?.tortoise;

@shangguanhonglei shangguanhonglei changed the title js技巧 js新特性 May 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant