
// 这份代码片段基于Public Domain发布 String.format = functiontpl) { var index = 1, items = arguments; return (tpl || '').replace(/{(\w*)}/g, function(match, p1) { return items[index++] || p1 || match; }); }; String.prototype.format = function() { var index = 0, items = arguments; return this.replace(/{(\w*)}/g, function(match, p1) { return items[index++] || p1 || match; }); }; > 'test{}test{}'.format() < "test{}test{}" > 'test{}test{2}'.format('1') < "test1test2" > 'test{}test{2}'.format('1', '3') < "test1test3" 1 est 2015-05-14 10:16:01 +08:00 我还以为把 %03.3f 这种都实现了呢。 |
2 YuJianrong 2015-05-14 10:46:58 +08:00 首先请不要修改内置类型的prototype……其次很快ES6的String template就可以用了…… |
3 SoloCompany 2015-05-14 11:07:45 +08:00 |
4 qybei 2015-05-14 19:11:01 +08:00 via Android @YuJianrong 能说说不建议修改内置类型prototype的原因吗? |
5 YuJianrong 2015-05-15 01:05:06 +08:00 via iPad @qybei 两个原因: 1. 避免和其他库冲突,比如另一个库也手贱写了个String.format然后实现还不一样那两个必有一个工作不正常。 2. 避免和未来的新标准冲突(比如mootools早期版本自己实现了function.bind和JSON对象,然后过了一段时间ES5标准里加入了不一样的实现……) 所以唯一能接受的是为了在低版本浏览器上补足广泛接受的新特性而做的polyfill,比如补足IE8 的ES5支持的es5-shim,比如旧浏览器上用setTimeout模拟requestAnimationRefresh。 |