Maison > Questions et réponses > le corps du texte
var template1="我是{0},今年{1}了";
var template2="我是{name},今年{age}了";
var result1=template1.format("loogn",22);
var result2=template1.format({name:"loogn",age:22});
PHPz2017-04-11 09:50:46
这个需要你定义这个函数才能调用.顺便贴一下我代码:
<script type="text/javascript">
String.prototype.format = function() {
var resultStr = this.toString();
// 参数为对象
if(typeof arguments[0] === "object") {
for(var i in arguments[0]) {
resultStr = resultStr.replace("{" + i + "}", arguments[0][i]);
}
}
// 多个参数
else {
for(var i = 0; i < arguments.length; i ++) {
resultStr = resultStr.replace("{" + i + "}", arguments[i]);
}
}
return resultStr;
};
var template1 = "我是{0},今年{1}了";
var template2 = "我是{name},今年{age}了";
var result1 = template1.format("loogn",22);
var result2 = template2.format({name:"loogn",age:22});
console.log("result1: " + result1);
console.log("result2: " + result2);
</script>
结果图: