猿问

类型错误:未定义不是构造函数

我有这样的代码:

const rtf = new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" });

在 Safari/605.1.15 中触发错误:

TypeError: undefined is not a constructor (evaluating 'new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" })')

现代 JS 中的一个如何解决 Intl API 可能不存在的事实?


蝴蝶刀刀
浏览 311回答 1
1回答

子衿沉夜

这种方法没有得到很好的支持。我可以使用相对时间格式吗?您可以做的是使用一个包来模拟您需要的功能,无论浏览器是什么。我找到了您可以使用的相对时间格式npm 包。安装npm install 相对时间格式 --save用import RelativeTimeFormat from "relative-time-format"import en from "relative-time-format/locale/en.json"RelativeTimeFormat.addLocale(en)// Returns "2 days ago"new RelativeTimeFormat("en", {  style: "long" // "long" is the default. Other options: "short", "narrow".}).format(-2, "day")要检查浏览器是否兼容:if (Intl === void 0 || typeof Intl.RelativeTimeFormat !== 'function') {   // Browser not compatible}选择 :const rtf = (Intl &&            Intl.RelativeTimeFormat &&            new Intl.RelativeTimeFormat('en', {               style: 'short',               numeric: "auto",            })) || false;if (!rtf) {   // Not compatible}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答