我对下面这段用 JS 编写的代码感兴趣:
const array = [1,2,3];
const locales = 'en-US';
const options = null;
console.log(array.toLocaleString(locales,options));
在 Node.js 20 之前,这将输出 1,2,3。然而,在 Node.js 20 中,它现在抛出以下错误:
Uncaught TypeError: Number.prototype.toLocaleString called on null or undefined
at Number.toLocaleString (<anonymous>)
at Array.toLocaleString (<anonymous>)
我试图了解实施过程中发生了什么变化。具体来说,我正在寻找源代码中更改的确切代码行。我查看了 ECMAScript 语言规范,但找不到任何相关的更改。我的重点是确定代码在实现中发生了哪些变化,而不是理解其背后的原因。请指出我正确的方向。
产生这个问题的原因是因为我有一个库引入了新的数据结构并提供了与
array
类似的方法。我希望我的 DS 和数组对于任何类型的输入都具有相同的结果,包括 null
。一旦我注意到版本之间,toLocaleString
提供了不同的结果,我就明白我需要更新我自己的toLocaleString
以支持最新的更改。为了做到这一点,我试图找出确切的变化,以便亲眼看到变化。
现代 Chrome 浏览器也会引发错误。
options
参数预计为 object|undefined
。将 null
传递给可选对象参数是不合法的。
我相信 V8 正在远离被视为
null
的 undefined
,因为它不能很好地与 TypeScript 语言配合使用。
在下面的 TypeScript 代码中,您可以看到 TS2345 错误。在 TypeScript 中,可选参数
?
被解释为该类型或 undefined
。
const aNumber: number = 42;
aNumber.toLocaleString('en', null);
// ----
// Argument of type 'null' is not assignable to parameter
// of type 'NumberFormatOptions | undefined'.
// (2345)
这里是
Number.prototype.toLocaleString
方法的 TypeScript 类型签名,供参考:
(method) Number.toLocaleString(
locales?: string | string[],
options?: Intl.NumberFormatOptions
): string