[Javascript] template literal tag

function currency(strings, ...values) {
    return strings.reduce((result, string, i) => {
        let value = values[i - 1];
        if (typeof value === "number") {
            value = `$${value.toFixed(2)}`;
        }
        return result + value + string;
    });
}

const price = 19.5005;
const formatted = currency`The total price is ${price}.`;

console.log(formatted); // The total price is $19.50.

 

posted @ 2024-06-16 03:23  Zhentiw  阅读(5)  评论(0编辑  收藏  举报