Node.js 20中Array.prototype.toLocaleString实现变更定位求助
Node.js 20中Array.prototype.toLocaleString的源码变更定位
复现代码
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>)
具体源码变更位置
这个变更来自Node.js升级V8引擎到11.3版本时的改动,核心是数组toLocaleString方法对options参数的处理逻辑变化:
- 旧实现(Node.js 19及更早):当
options为null时,会自动转为undefined,再传给每个元素的toLocaleString - 新实现(Node.js 20及以后):直接把
null作为第二个参数传给元素的toLocaleString,而Number.prototype.toLocaleString不接受null作为第二个参数,因此报错
在Node.js的源码仓库中,变更集中在deps/v8目录下的数组方法实现文件里,具体是修改了数组toLocaleString遍历元素时的参数传递逻辑——移除了将null转为undefined的处理步骤。
适配你的类数组结构
要让你的类数组toLocaleString和原生数组行为一致,需要:
- 检查传入的
options参数,若为null,则替换为undefined后再传递给每个元素的toLocaleString(兼容全版本) - 或者直接传递
null,但要处理元素方法可能抛出的错误(仅适配Node.js 20+)
内容的提问来源于stack exchange,提问作者vesii
相关产品推荐
相关产品推荐

