返回信息流function forEach(obj, iterator, context) {
if (obj.length === +obj.length) {
for (var i = 0, len = obj.length; i < len; i++) {
iterator.call(context, obj[i], i, obj);
}
} else {
for (var key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
}
function formatString(s) {
forEach(typeof arguments[1] === "string" ? Array.prototype.slice.call(arguments, 1) : arguments[1], function () {
eval("s = s.replace(/\\{" + arguments[1] + "\\}/g, arguments[0]);");
});
return s;
}
var template_with_number = "{0}, my name is {1}, I hate {2}!";
alert(formatString(template_with_number, "Hello", "Brendan Eich", "javascript"));
alert(formatString(template_with_number, ["Hi", "John Resig", "jQuery"]));
var template_with_json = "{greetings}, my name is {name}, I love {job}!";
alert(formatString(template_with_json, { greetings : "Nice to meet you", name : "WYKM", job : "front end"}));
这是一条镜像帖。来源:北邮人论坛 / www-technology / #25426同步于 2014/5/6
该镜像源已超过 30 天没有更新,可能在源站已被删除。
WWWTechnology机器人发帖
FormatString
wykm
2014/5/6镜像同步1 回复
订阅后,新回复会通过你的通知中心匿名送达。
1 条回复
function formatString(template, data) {
return typeof data === "string" ? arguments.callee(template, Array.prototype.slice.call(arguments, 1)) : template.replace(/{([^{}]*?)}/g, function (match, key) {
return data[key] == null ? match : data[key];
});
}
var template_with_number = "{0}, my name is {1}, I hate {2}!";
alert(formatString(template_with_number, "Hello", "Brendan Eich", "javascript"));
alert(formatString(template_with_number, ["Hi", "John Resig", "jQuery"]));
var template_with_json = "{greetings}, my name is {name}, I love {job}!";
alert(formatString(template_with_json, { greetings : "Nice to meet you", name : "WYKM", job : "front end"}));
//Caution: ES5 forbids use of arguments.callee() in strict mode.