Python 有一个漂亮的函数来转这个:
Python has this beautiful function to turn this:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar
进入这个:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar
JavaScript有这样的功能吗?如果不是,我将如何创建一个遵循与 Python 实现相同的语法?
Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?
另一种方法,使用 String.prototype.replace
方法,第二个参数是replacer"函数:
Another approach, using the String.prototype.replace
method, with a "replacer" function as second argument:
String.prototype.format = function () {
var i = 0, args = arguments;
return this.replace(/{}/g, function () {
return typeof args[i] != 'undefined' ? args[i++] : '';
});
};
var bar1 = 'foobar',
bar2 = 'jumped',
bar3 = 'dog';
'The lazy {} {} over the {}'.format(bar3, bar2, bar1);
// "The lazy dog jumped over the foobar"
这篇关于JavaScript 等效于 Python 的 format() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!