Javascript Intl.NumberFormat问题

问题描述 投票:2回答:2

有人可以解释为什么以下代码不起作用,除非我硬编码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>
javascript currency
2个回答
3
投票

问题是这部分:

currency: '${currency}'

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

你需要这个:

currency: `${currency}`

要不就

currency: currency

甚至,Spock先生在评论中提到的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));

2
投票

你的代码工作正常,没有像这样的json:

var config = {  style: 'currency',  currency: currency, minimumFractionDigits: 0,  maximumFractionDigits: 0 };
cf = new Intl.NumberFormat(locale, config);
cf.format(123);
© www.soinside.com 2019 - 2024. All rights reserved.