测试 toLocaleString 支持

Testing for toLocaleString support

我使用 toLocaleString 来格式化英国的工作薪水,像这样传递货币选项:

tempSalary = parseInt(salary).toLocaleString('en-gb', { style: 'currency', currency: 'GBP'});

我知道这在 Safari 中无法正确实现,但我可以提前检查以输出其他内容吗?根据 the MDN description,我可以检查区域设置和选项参数吗?如果不支持,请不要为脚本操心?

我宁愿检查是否支持,也不愿检查是否使用 Safari(因为 IE10- 也不完全支持它)。

也许你可以按照MDN的建议做一个函数。并相应地处理错误。

function toLocaleStringSupportsLocales() {
  var number = 0;
  try {
    number.toLocaleString('i');
  } catch (e) {
    return e​.name === 'RangeError';
  }
  return false;
}

ECMA-402 表示要支持 Number.prototype.toString 的选项,实现必须:

  1. 与 ECMAScript Ed 5.1 及其后续版本保持一致
  2. 扩展内置 Number.prototype
  3. 实现一个 Intl 全局对象
  4. 支持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

但是,实现中可能存在错误。我能想到的唯一可能发生的是有些人可能不会 return typeof 的预期值,即使它们是必需的(例如,过去有浏览器return 'unknown' 而不是 'object' 或 'object' 而不是 'function')。此外,如果提供 options 参数,ECMA-262 ed 3 实现不需要抛出错误,因此基于 try..catch 的检测在这些主机中可能会失败。

以下是一个更宽容的版本(但我会使用上面的版本,直到我发现需要它的主机):

function toLocaleStringSupportsOptions() {
  return !!(typeof Intl != 'undefined' && Intl && typeof Intl.NumberFormat != 'undefined');
}