JS原生并没有提供方便使用的Formatter函数,用字符拼接的方式看起来混乱难读,而且使用起来很不方便。个人感觉C#里提供的语法比较好用,如:
1 String.Format(“Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love");这种有顺序的替换方式,比较清晰,而且在要替换同一内容时候可以省去传递重复参数的情况,下面是JS简单实现版本(没有严格测试):
01 (function(exports) { 02 exports.format = function(){ 03 var args = Array.prototype.slice.call(arguments), 04 sourceStr = args.shift(); 05 06 function execReplace(text,replacement,index){ 07 return text.replace(new RegExp("{"+index+"}",'g'),replacement); 08 } 09 10 return args.reduce(execReplace,sourceStr); 11 } 12 })(window.utils = window.utils || {}); 13 14 console.log(utils.format("Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love"));关键的是这句:
1 args.reduce(execReplace,sourceStr);这里使用了Array的reduce函数,reduce和reduceRight是ES5新增加的函数,该函数的参数是reduce(callback,initialValue),callback接收4个参数分别是:
previousValue:
在遍历第一次进入该回调函数时,如果指定了initivalValue将直接使用initivalValue,如果没有指定将使用数组的第一个元素
第二次及以后的遍历该值是前一次遍历返回的结果
最后一次遍历返回的结果将作为reduce函数的返回值
currentValue: 遍历到的当前item
index: 当前item在数组中的下标
array: 原始array
在execReplace中每一次执行时使用前一次替换后的结果作为原始替换字符串,使用当前item的index作为要被替换的内容,依次遍历,最终完成替换内容。
注:reduceRight和reduce函数基本一样,只是它的遍历顺序是由右向左