【问题标题】:Issue with Javascript Intl.NumberFormatJavascript Intl.NumberFormat 问题
【发布时间】:2018-04-29 21:11:17
【问题描述】:

谁能解释为什么除非我对 json 进行硬编码,否则以下代码不起作用?我希望能够交换各种语言环境、货币值。

<html>
<body>
<script>

    currency = 'GBP';
    locale = 'en-GB';

    var json = `{  style: 'currency',  currency: '${currency}', minimumFractionDigits: 0,  maximumFractionDigits: 0 }`;
        console.log(json);
        cf = new Intl.NumberFormat(locale, json);
        document.write(cf.format(1887732.233) + "<br>");

</script>
</body>
</html>

【问题讨论】:

  • 不清楚您所说的“除非我对 json 进行硬编码”是什么意思?你想做什么?
  • 你的“json”是一个对象文字,“en-GB”不是一个语言环境,它是一个语言代码。 Intl 对象接受一个选项对象,其属性和名称用作生成字符串的值。您真的在问如何使用变量生成该对象吗?
  • 通过对 json 进行硬编码,我的意思是使用每种语言的所有文字重复 json。我宁愿在那个 json 参数中使用一个变量,而不是重复它 50 次。
  • 是的,我想避免为每种语言代码创建 50 个不同版本的 json。我想在那个 json 中插入一个变量
  • @RobG,我之所以说 locale,是因为我在developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…看到了这个文档 new Intl.NumberFormat([locales[, options]])

标签: javascript currency


【解决方案1】:

问题出在这部分:

currency: '${currency}'

这不是template literal,而只是一个字符串。

你需要这个:

currency: `${currency}`

或者只是

currency: currency

甚至,Spock 先生在 cmets 中提到的,带有一个short hand property

currency

var currency = 'GBP',
    locale = 'en-GB';
    json = {
        style: 'currency',
        currency,
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
    };

console.log(json);
cf = new Intl.NumberFormat(locale, json);

console.log(cf.format(1887732.233));

【讨论】:

  • { currency: currency } 可以写成 { currency }
【解决方案2】:

如果没有这样的 json,您的代码也可以正常工作:

var config = {  style: 'currency',  currency: currency, minimumFractionDigits: 0,  maximumFractionDigits: 0 };
cf = new Intl.NumberFormat(locale, config);
cf.format(123);

【讨论】:

    猜你喜欢
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2020-05-31
    相关资源
    最近更新 更多