Проблема с Javascript Intl.NumberFormat - PullRequest
0 голосов
/ 30 апреля 2018

Может кто-нибудь объяснить, почему следующий код не работает, если я жестко не кодирую 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>

Ответы [ 2 ]

0 голосов
/ 30 апреля 2018

Проблема в этой части:

currency: '${currency}'

, который не является литералом шаблона , а просто строкой.

Вам нужно это вместо:

currency: `${currency}`

или просто

currency: currency

или даже, который г-н Спок в упомянутых комментариях, с свойством короткой руки

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));
0 голосов
/ 30 апреля 2018

Ваш код работает без JSON, вот так:

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