文章出處
文章列表
在寫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;
}
簡單數組
"{0}|{1}|{2}".format([2,3,4]); // 2|3|4 "{0}|{1}|{2}".format(["a","b","c"]); // a|b|c
簡單多參數
"{0}|{1}|{2}".format(2,3,4); // 2|3|4 "{0}|{1}|{2}".format("a","b","c"); // a|b|c
數組多參數
"{0}|{1}|{2}".format([1,2,3],[4,5,6]); // 1|2|34|5|6
對象多參數
"<li value='{v}'>{n}</li>".format({v:1,n:'n1'},{v:2,n:'n2'}); // <li value="1">n1</li><li value="2">n2</li>
簡單對象
"{a}|{b}|{c}".format({a:1,b:"ef",c:23}); //1|ef|23
數組數組
"{0}|{1}|{2}".format([[1,2,3],[4,5,6]]); // 1|2|34|5|6
對象數組
"<li value='{v}'>{n}</li>".format([{v:1,n:'n1'},{v:2,n:'n2'}]); // <li value="1">n1</li><li value="2">n2</li>
文章列表
全站熱搜