为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶刀刀 2021-11-12 17:12:21
我有这样的代码: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 可能不存在的事实?
查看完整描述

1 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

这种方法没有得到很好的支持。我可以使用相对时间格式吗?

//img1.sycdn.imooc.com//618e301e0001667812620311.jpg

您可以做的是使用一个包来模拟您需要的功能,无论浏览器是什么。


我找到了您可以使用的相对时间格式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

}


查看完整回答
反对 回复 2021-11-12
  • 1 回答
  • 0 关注
  • 310 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信