我使用 toLocaleString
来格式化英国工作工资,传递货币选项,如下所示:
tempSalary = parseInt(salary).toLocaleString('en-gb', { style: 'currency', currency: 'GBP'});
我知道这在 Safari 中无法正确实现,但我可以提前检查以输出其他内容吗?根据the MDN description ,我可以检查区域设置和选项参数吗?如果不支持,则不要使用脚本?
我宁愿检查支持,而不仅仅是检查是否使用 Safari(因为 IE10 - 也不完全支持它)。
最佳答案
ECMA-402表示要支持 Number.prototype.toString 的选项,实现必须:
- 与 ECMAScript Ed 5.1 及其后续版本保持一致
- 扩展内置的Number.prototype
- 实现一个Intl全局对象
- 支持Intl.NumberFormat构造函数
基于此,支持测试是:
if (typeof Intl == 'object' && typeof Intl.NumberFormat == 'function') {
// toLocaleString with options supported
} else {
// host dependent
}
作为函数:
function toLocaleStringSupportsOptions() {
return !!(typeof Intl == 'object' && Intl && typeof Intl.NumberFormat == 'function');
}
当然,它必须经过广泛的测试。它可以在我测试的几种更流行的浏览器中运行,有些支持或不支持 Intl.NumberFormat。
但是,实现中可能存在错误。我能想到的唯一可能发生的情况是,有些浏览器可能不会返回 typeof 的预期值,即使它们被要求这样做(例如,过去有些浏览器返回“未知”而不是“对象”或“对象”而不是“函数”)。此外,如果提供了 options 参数,ECMA-262 ed 3 实现不需要抛出错误,因此基于 try..catch 的检测可能在这些主机中失败。
以下是一个更宽容的版本(但我会使用上面的版本,直到我发现需要它的主机):
function toLocaleStringSupportsOptions() {
return !!(typeof Intl != 'undefined' && Intl && typeof Intl.NumberFormat != 'undefined');
}
关于javascript - 测试 toLocaleString 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31871771/