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);运行说没有这个方法??

解决方案 »

  1.   

    报错是对象不支持此属性或方法应该是为String对象原型添加format()方法时出了问题
      

  2.   


    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);
      

  3.   

    为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);