Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:undefined不是构造函数(计算新的Intl.RelativeTimeFormat(';en&';,{样式:';短';,数字:&"auto&"';)_Javascript - Fatal编程技术网

Javascript TypeError:undefined不是构造函数(计算新的Intl.RelativeTimeFormat(';en&';,{样式:';短';,数字:&"auto&"';)

Javascript TypeError:undefined不是构造函数(计算新的Intl.RelativeTimeFormat(';en&';,{样式:';短';,数字:&"auto&"';),javascript,Javascript,我有如下代码: 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" })') 现代

我有如下代码:

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可能不存在的问题?

这种方法没有得到很好的支持

无论浏览器是什么,您都可以使用一个模拟所需功能的软件包

我发现你可以使用npm软件包


安装

npm安装相对时间格式--保存

使用

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
}

我不想用包裹。我只需要一种方法来判断不支持rtf的浏览器中何时存在rtf。“人们会尝试……接球吗?”亨德利:那好吧。我已经添加了如何检查函数是否存在,如何将
constrtf
设置为可以使用或检查的内容?e、 g.
if(rtf){id.innerHTML=rtf.format(parseInt(seconds/60),'minute');}else{id.innerHTML=parseInt(seconds/60)+“m”}
@hendry我添加了一个替代选项,这样您就可以直接在
rtf
值上进行检查