这段代码怎么不行?

focuserp 2010-09-05 12:02:01
String.prototype.format=function(format)
{
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/\{(\d+)\}/g,function(m,i){ return args[i];});
}
var cls = 'my-class', text = 'Some text';
var s =String.format('<div class="{0}">{1}</div>', cls, text);
alert(s);

运行说没有这个方法??
...全文
80 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
qingYun1029 2010-09-05
  • 打赏
  • 举报
回复
报错是对象不支持此属性或方法。。。

应该是为String对象原型添加format()方法时出了问题。。。
qingYun1029 2010-09-05
  • 打赏
  • 举报
回复
prototype不熟悉。。。

加强学习了。。
cc6412223 2010-09-05
  • 打赏
  • 举报
回复
为String添加静态方法:
String.format=function(format)
{
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/\{(\d+)\}/g,function(m,i){ return args[i];});
}
var cls = 'my-class', text = 'Some text';
var s =String.format('<div class="{0}">{1}</div>', cls, text);
alert(s);
s_liangchao1s 2010-09-05
  • 打赏
  • 举报
回复

String.prototype.format=function()
{
var args = Array.prototype.slice.call(arguments, 0);
return this.replace(/\{(\d+)\}/g,function(m,i){ return args[i];});
}
var cls = 'my-class', text = 'Some text';
var s = '<div class="{0}">{1}</div>'.format(cls, text);
alert(s);

87,917

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧