我正在开发一个React.js Web应用程序,其中包含使用Intl(国际化对象)的数据表。仅当尝试在旧的Safari浏览器上加载应用程序时,才会出现以下错误。
这是当前用于检查Intl
是否可用以及是否退回到localCompare()
function getCollatorComparator() {
if (Intl) return new Intl.Collator(void 0, { numeric: !0, sensitivity: "base" }).compare;
return function(e, t) {
return (e + "").localeCompare(t)
}
}
以上代码在旧版Safari(iOS 9)上不起作用。
如何检查Intl
是否可用?
答案 0 :(得分:1)
When you do if(Intl)
you're going to get an error as Intl
is not defined, similarly to this:
if(foo) { // foo not defined -> thus crash
console.log("foo");
} else {
console.log("bar"); // not executed
}
However, if you use typeof
, you can check if a varaible hasn't been declared before:
if(typeof foo !== "undefined") { // no crash (foo is undefined)
console.log("foo");
} else {
console.log("bar"); // bar is outputted
}
Thus, instead of using (which throws an error if Intl
isn't defined):
if(Intl) // code...
you can use:
if(typeof Intl !== "undefined") // code...