gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:05:06 28 4
gpt4 key购买 nike

我正在使用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"});
}
});

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

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 || ","
]);
});

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

关于javascript - 如何将参数对象传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859097/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com