Javascript:未定义字符串的格式

nav*_*yad 6 javascript

我有以下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)


Ort*_*iel 5

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)