如何将参数对象传递给函数?

How to transmit an arguments object to a function?

我正在与 handlebars.js 打交道,我想借助助手来格式化一些数字。为了格式化数字,我发现 accounting.js 库似乎符合我的期望。要格式化数字,我可以使用:

// Simple `format` string allows control of symbol position (%v = value, %s = symbol):
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

这是我现在的帮手:

Handlebars.registerHelper('amount', function(item) {
    if (item == null) {
        return "-"; 
    } else {    
        return accounting.formatMoney(item,{symbol: "EUR",  format: "%v %s"});                                       
    }
});

这可行,但使用起来有点严格,我希望能够将我的数字格式化为一个选项。我的新帮手将是:

Handlebars.registerHelper('amount', function(item, options) {
    if (item == null) {
        return "-"; 
    } else {    
        return accounting.formatMoney(item,options);                                       
    }
});

问题是它不起作用,因为我不知道如何将对象传递给工作人员。这是我在模板中的调用

{{amount programme.amountIssued {symbol: "EUR",  format: "%v %s"} }}

这给了我以下结果:

handlebars.js:1659 Uncaught Error: Parse error on line 87:
...gramme.amountIssued {symbol: "EUR",  for
-----------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'

如果我将它与周围的引号一起使用,并且内部的引号用 \ 评论:

{{amount programme.amountIssued "{symbol: \"EUR\",  format: \"%v %s\"}" }}

这已执行,但结果不是预期的结果:

{symbol: "EUR", format: "4,000,000,000.00 %s"}%v

而不是 4,000,000,000.00 欧元

您不能将参数传递给带有对象的 JS 函数。但是您可以将它们作为数组传递。这是通过 .apply (docs).

完成的

为了易读性包装并包括每个选项的默认值:

Handlebars.registerHelper('amount', function (item, options) {
    if (item == null) return "-"; 

    return accounting.formatMoney.apply(accounting, [
        item,
        options.symbol || "",
        options.precision || 2,
        options.thousands || ".",
        options.decimal || ","
    ]);                                       
});

此处函数应用于值数组(操作的名称由此而来),其中每个数组位置与函数期望的参数位置相匹配。