Python具有以下功能:
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实现相同的语法?
使用该String.prototype.replace
方法的另一种方法是将“替换器”功能作为第二个参数:
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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句