1.逻辑赋值操作符
你有遇到过这样的状况吗?
function example(a) { // Default `a` to "foo" if (!a) { a = "foo"; } // or a = a || "foo";}
某些初始化的时候须要一些简短的逻辑代码
function example(opts) { // Ok, but could trigger setter. opts.foo = opts.foo ?? "bar"; // No setter, but 'feels wrong' to write. opts.baz ?? (opts.baz = "qux");}example({ foo: "foo" });
function example(opts) { // 旧的形式 if (!a) { a = "foo"; } // or a = a || "foo"; // 新的形式 a ||= "foo"}example({ foo: "foo" });
function example(opts) { // 旧的形式 opts.foo = opts.foo ?? "bar"; // 新的形式 opts.foo ??= "bar"; // 旧的形式 opts.baz ?? (opts.baz = "qux"); // 新的形式 opts.baz ??= "qux";}example({ foo: "foo" });
a = a + b;a += b;a = a - b;a -= b;
2.Promise.any
Promise.any
。 从字面意思来看,置信聪慧的你应该能大抵猜出这个 API 的作用。Promise.any
承受一个 Promise
的数组。当其中任何一个 Promise
实现(fullfill)时,就返回那个曾经有实现值的 Promise
。如果所有的 Promise
都回绝(reject),则返回一个回绝的 Promise
,该 Promise
的返回值是一个 AggregateError
对象。
Promise.any(promises).then( (first) => { // 任意一个Promise实现了 }, (error) => { // 所有Promise都被回绝了 });
Promise.any([ fetch("https://v8.dev/").then(() => "home"), fetch("https://v8.dev/blog").then(() => "blog"), fetch("https://v8.dev/docs").then(() => "docs"),]) .then((first) => { // Any of the promises was fulfilled. console.log(first); // → 'home' }) .catch((error) => { // All of the promises were rejected. console.log(error); });
例如一些播放平台,能够通过这个来测试以后提早最低的线路是哪个,优先切换到对应的最快的线路。
来,亮出祖传降级代码
function reverse(promise) { return new Promise((resolve, reject) => Promise.resolve(promise).then(reject, resolve) );}function promiseAny(iterable) { return reverse(Promise.all([...iterable].map(reverse)));}// https://github.com/m0ppers/promise-any/blob/master/index.js
实现很简略,通过一个反转函数,利用 Promisea.all
的个性,只有一个 Promise
被回绝了,就进入到 reject
,因而反转 resolve
和 reject
就能模拟出 Promise.any
了。
3.数字分隔符
let fee = 1000000000;let fee = 1_000_000_000;
这个模式不仅在十进制能够用,二进制,十六进制....甚至 BigInt,都能够应用。
// Binary Literalslet nibbles = 0b1010_0001_1000_0101;// Hex Literallet message = 0xa0_b0_c0;// BigInt Literalconst max = 2n ** (64n - 1n) - 1n;console.log(max === 9_223_372_036_854_775_807n);
以上个性均在最新版 chrome
反对,快关上控制台游玩吧。
如果想要在理论我的项目中应用,请应用以下两个插件。
- Logical Assignment Operator
- Numeric Separator