萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現類 C# String.Format 的格式化函數(基於 Array.reduce)

需求背景

JS 原生無 String.Format,字串拼接易讀性差:

// 傳統拼接
var msg = "Welcome to learn '" + lang + "', '" + lang + "' is awesome, you will " + action + " it!";
// 模板字串 (ES6) 雖好,但無法復用模板、無法按索引多次引用同一參數

輕量級 Format 實現(< 20 行)

;(function(exports) {
  exports.format = function() {
    var args = Array.prototype.slice.call(arguments);
    var template = args.shift(); // 第一個參數為模板字串

    // 核心:reduce 依次替換 {0}, {1}...
    return args.reduce(function(currentTemplate, replacement, index) {
      return currentTemplate.replace(new RegExp('\\{' + index + '\\}', 'g'), replacement);
    }, template);
  };
})(window.utils = window.utils || {});

使用示例

console.log(utils.format(
  "Welcome to learn '{0}', '{0}' is awesome, you will {1} it!",
  "JavaScript", "love"
));
// 輸出: Welcome to learn 'JavaScript', 'JavaScript' is awesome, you will love it!

核心原理:Array.reduce 鏈式替換

args.reduce(callback, initialValue)
// callback(previousValue, currentValue, index, array)
// previousValue: 上一次返回結果 (初始為 template)
// currentValue: 當前參數值 (args[index])
// index: 當前索引 (0, 1, 2...)
// 每輪將 {index} 替換為 currentValue,結果傳遞給下一輪

流程圖解:

template: "A{0}B{1}{0}"
args: ["X", "Y"]

第1輪 (index=0): replace("{0}", "X") → "AXB{1}X"
第2輪 (index=1): replace("{1}", "Y") → "AXBYX"
返回 "AXBYX"

功能增強版(支援對象屬性、轉義、自定義分隔符)

utils.format = function(template) {
  var args = Array.prototype.slice.call(arguments, 1);
  // 支援單個對象參數:format("{name}", {name:"A"})
  if (args.length === 1 && typeof args[0] === 'object') {
    args = args[0];
  }
  return template.replace(/\{(\w+)\}/g, function(match, key) {
    return args.hasOwnProperty(key) ? args[key] : match; // 找不到保留原樣
  });
};

// 使用
utils.format("Hello {name}, age {age}", {name: "Tom", age: 18});
utils.format("Hello {0}, age {1}", "Tom", 18); // 兼容索引

性能對比

方案原理性能特點
reduce + 正則替換n 次正則替換 (n=參數數)中代碼極簡、支援索引重複引用
單次正則 + 回調1 次正則掃描,回調查表高需處理對象/陣列統一、不支援重複索引 (需額外邏輯)
模板字串 (ES6)引擎原生最高無法復用模板、無法動態構建模板
sprintf-js 等庫完整 printf 語法中功能全、體積大

總結

  • reduce 實現極其優雅,適合輕量級場景(工具函數、日誌格式化)。
  • 生產環境高頻調用建議用單次正則版或成熟庫(sprintf-js、format-util)。
  • ES6 模板字串解決 90% 場景,format 針對「模板復用、動態模板、索引重複引用」補位。
copyright © 萬盛學電腦網 all rights reserved