JavaScript:最新第四阶段功能
由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!
以下功能在最近的TC39会议上进入了第四阶段:
- 国际日期时间格式:dateStyle 和 timeStyle
- 国际列表格式。
- 逻辑赋值。
- 数字分隔符。
- Promise.any 和 AggregateError。
- WeakRefs 和 FinalizationRegister。
让我们来看一个简单的代码示例:
国际日期时间格式
该提案为 Intl.DateTimeFormat 添加了两个选项:dateStyle 和 timeStyle。
let date = new Intl.DateTimeFormat("en" , {
timeStyle: "medium",
dateStyle: "short"
});
date.format(Date.now()); // "01.02.2020, 13:30"
// styles: undefined, "full", "long", "medium", or "short"
国际列表格式
该提案支持语言敏感的列表格式化
const lf = new Intl.ListFormat("en", {
localeMatcher: "best fit", // can be "lookup"
type: "conjunction", // "conjunction", "disjunction" or "unit"
style: "long", // other values: "short" or "narrow"
});
lf.format(['Apple', 'Orange' , 'Plum']);
// > "Apple, Orange, and Plum"
/*
localeMatcher -> "best fit" or "lookup"
type -> "conjunction", "disjunction" or "unit"
style -> "long", "short" or "narrow"
*/
逻辑分配
该方案允许将逻辑运算符和赋值表达式结合起来。
// "Or Or Equals" (or, the Mallet operator :wink:)
a ||= b;
a || (a = b);
// "And And Equals"
a &&= b;
a && (a = b);
// "QQ Equals"
a ??= b;
a ?? (a = b);
数字分隔符。
该提案是将
proposal-numeric-underscores现有方案合并,NumericLiteral以允许在数字之间使用分隔符。
1_000_000_000 // Billion
101_475_938.38 // Hundreds of millions
let fee = 123_00; // $123
let hex = 0xA0_B0_C0;
let octal = 0o1234_5670;
Promise.any 和 AggregateError。
该提案接受
Promise.any一个包含多个承诺的可迭代对象,并返回一个由第一个被满足的承诺所满足的承诺,或者返回一个被拒绝的承诺。AggregateError
try {
const first = await Promise.any(promises);
// Any of the promises was fulfilled.
} catch (error) {
// All of the promises were rejected.
}
const aggregateError = new AggregateError([errA, errB, errC], 'Oops!');
WeakRefs 和 FinalizationRegistry。
该提案允许使用类创建对对象的弱引用,并在对象被垃圾回收后
WeakRef运行终结器。user-definedFinalizationRegistry
const makeWeakCached = f => {
const cache = new Map();
const cleanup = new FinalizationRegistry(key => {
const ref = cache.get(key);
if (ref && !ref.deref()) cache.delete(key);
});
return key => {
const ref = cache.get(key);
if (ref) {
const cached = ref.deref();
// See note below on concurrency considerations.
if (cached !== undefined) return cached;
}
const fresh = f(key);
cache.set(key, new WeakRef(fresh));
cleanup.register(fresh, key);
return fresh;
};
}
const getImageCached = makeWeakCached(getImage);
希望你喜欢这些方案,欢迎留言分享你的想法!🤓
--
@gnumanth