Home > Web Front-end > JS Tutorial > body text

Example code for implementing simple Formatter function in JS_javascript skills

WBOY
Release: 2016-05-16 16:39:15
Original
1467 people have browsed it

JS原生并没有提供方便使用的Formatter函数,用字符拼接的方式看起来混乱难读,而且使用起来很不方便。个人感觉C#里提供的语法比较好用,如:

String.Format(“Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love");
Copy after login

这种有顺序的替换方式,比较清晰,而且在要替换同一内容时候可以省去传递重复参数的情况,下面是JS简单实现版本(没有严格测试):

(function(exports) {
exports.format = function(){
var args = Array.prototype.slice.call(arguments),
sourceStr = args.shift();

function execReplace(text,replacement,index){
return text.replace(new RegExp("\\{"+index+"\\}",'g'),replacement);
}

return args.reduce(execReplace,sourceStr);
}
})(window.utils = window.utils || {});

console.log(utils.format("Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love"));
Copy after login

关键的是这句:

args.reduce(execReplace,sourceStr);
Copy after login

这里使用了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函数基本一样,只是它的遍历顺序是由右向左

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!