如何将参数应用于String.prototype.format函数

How to apply arguments to String.prototype.format function

本文关键字:prototype format 函数 String 应用于 参数      更新时间:2023-09-26

我试图在谷歌上搜索如何将参数动态应用于String.prototype.format函数,但我找不到任何我能理解的东西。colsEdit数组可以包含可变数量。

if (!String.prototype.format) {
  String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{('d+)}/g, function (match, number) {
      return typeof args[number] != 'undefined'
        ? args[number]
        : match;
    });
  };
}
colsEdit =
[
  { name: 'Amount', text: 'Amount', required: true, type: 'Numeric', value: 0, default: '' },
  { name: 'Date', text: 'Date', required: true, type: 'Date', value: '', default: new Date().format('yyyy-MM-dd') },
  { name: 'CostTypeId', text: 'Cost type', required: true, type: 'Select', value: 0, default: 1, dataSource: [] },
  { name: 'CurrencyId', text: 'Currency', required: true, type: 'Select', value: 0, default: 9,  dataSource: [] },
  { name: 'CountryId', text: 'Country', required: true, type: 'Select', value: 0, default: 16, dataSource: [] },
  { name: 'Description', text: 'Description', type: 'Text', value: '', default: '' }
];
var sql = 'insert into MON_Costs (Amount, Date, CostTypeId, CurrencyId, CountryId, Description) values({0}, STRFTIME("%Y-%m-%d", "{1}"), {2}, {3}, {4}, "{5}")';
var args = [];
var id = 1;//just test
for (var i = 0; i < colsEdit.length; i++) {
  args.push($('#__{0}'.format(colsEdit[i].name)).val());
}
args.push(id);
sql = sql.format(); //how to add args to format function???

您正在寻找函数的apply方法:

sql = sql.format.apply(sql, args);