一个简单确非常实用的javascript函数

在写js的时候,往往会碰到字符串拼接的问题,如果简单,直接使用+号连接字符串就可以了, 但是如果复杂,+用起来就非常不爽,在.net中有,Sting.Format函数,用起来还是很爽的,于是就想着js中是不是有类似的函数,答案是没有,但是js可以扩展原型,于是在网上找到很多版本的format, 功能都比较简单,也挺实用。 经过我一些思考,改造,扩展了format函数的功能, 个人感觉挺实用,代码也非常少,所以发出来共享下, 废话不多说,直接上码,代码很少,不解释。

String.prototype.format = function() {

    var args,
ret = '',
type = Object.prototype.toString.call(arguments[0]); if (type == "[object Object]") {
args = arguments;
} else if (type == "[object Array]") {
type = Object.prototype.toString.call(arguments[0][0]);
if (type == "[object Object]" || type == "[object Array]") {
args = arguments[0];
} else {
args = arguments;
}
} else {
args = [arguments];
} for (var i in args) {
var a = args[i];
ret += this.replace(/{([\w]+?)}/g, function(all, match) {
return a[match];
});
} return ret;
}
  1. 简单数组
    "{0}|{1}|{2}".format([2,3,4]);  // 2|3|4
"{0}|{1}|{2}".format(["a","b","c"]); // a|b|c
  1. 简单多参数
    "{0}|{1}|{2}".format(2,3,4);  // 2|3|4
"{0}|{1}|{2}".format("a","b","c"); // a|b|c
  1. 数组多参数
    "{0}|{1}|{2}".format([1,2,3],[4,5,6]);  // 1|2|34|5|6
  1. 对象多参数
    "<li value='{v}'>{n}</li>".format({v:1,n:'n1'},{v:2,n:'n2'});  // <li value="1">n1</li><li value="2">n2</li>
  1. 简单对象
    "{a}|{b}|{c}".format({a:1,b:"ef",c:23});  //1|ef|23
  1. 数组数组
    "{0}|{1}|{2}".format([[1,2,3],[4,5,6]]);  // 1|2|34|5|6
  1. 对象数组
    "<li value='{v}'>{n}</li>".format([{v:1,n:'n1'},{v:2,n:'n2'}]);  // <li value="1">n1</li><li value="2">n2</li>
上一篇:在MVC里面使用Response.Redirect方法后记得返回EmptyResult


下一篇:js 发送短信倒计时、秒杀倒计时实现代码