我有以下javascript代码片段:
var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));
Run Code Online (Sandbox Code Playgroud)
得到以下错误:
Uncaught TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)
我错过了什么,这里?
Koo*_*Inc 15
String.format
不是原生String
扩展.自己扩展它很容易:
String.prototype.format = function () {
var args = [].slice.call(arguments);
return this.replace(/(\{\d+\})/g, function (a){
return args[+(a.substr(1,a.length-2))||0];
});
};
// usage
'{0} world'.format('hello'); //=> 'hello world'
Run Code Online (Sandbox Code Playgroud)
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i += 1) {
var reg = new RegExp('\\{' + i + '\\}', 'gm');
s = s.replace(reg, arguments[i + 1]);
}
return s;
};
var strTempleate = String.format('hello {0}', 'Ortal');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12524 次 |
最近记录: |