Javascript:未定义字符串的格式 [英] Javascript: string's format is not defined
本文介绍了Javascript:未定义字符串的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下javascript代码片段:
I have following snippet of javascript code:
var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));
收到以下错误:
Uncaught TypeError: undefined is not a function
我缺少什么,这里?
推荐答案
String.format
不是原生字符串
扩展名。自己扩展它很容易:
String.format
is not a native String
extension. It's pretty easy to extend it yourself:
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'
这篇关于Javascript:未定义字符串的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文