标签:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <script type="text/javascript"> /* 1."{v1}你好,我是{v2},我今年{v3}岁了"; {v1:Cupid,v2:Tina,v3:18}; 2.‘{0}你好,我是{1},我今年{2}岁了‘;[‘Cupid‘, ‘Tina‘, 18]; 3.‘{0}你好,我是{1},我今年{2}岁了‘;‘Cupid‘, ‘Tina‘, 18; */ String.prototype.format = function (obj) { var that = this; if (typeof obj == "object") { for (var attr in obj) { that = that.replace("{" + attr + "}", obj[attr]); } } else { //var a = arguments; //alert(a instanceof Array)==》false //把参数放到数组里面 slice() 方法可从已有的数组中返回选定的元素。 var arr = [].slice.call(arguments, 1); //调用自己 return format(str, arr); } return that; } function format(str, obj) { if (typeof obj == "object") { for (var attr in obj) { str = str.replace("{" + attr + "}", obj[attr]); } } else { //var a = arguments; //alert(a instanceof Array)==》false //把参数放到数组里面 slice() 方法可从已有的数组中返回选定的元素。 var arr = [].slice.call(arguments, 1); //调用自己 format(str, arr); } return str; } var str = ‘{v1}你好,我是{v2},我今年{v3}岁了‘; var obj = { v1: ‘Cupid‘, v2: ‘Tina‘, v3: 18 }; console.log(format(str, obj));// Cupid你好,我是Tina,我今年18岁了; var ss = str.format(obj); console.log(ss);/// Cupid你好,我是Tina,我今年18岁了; var str1 = ‘{0}你好,我是{1},我今年{2}岁了‘; var obj1 = [‘Cupid‘, ‘Tina‘, 18]; console.log(format(str1, obj1)); var ss1 = str1.format(obj1); console.log(ss1); var str2 = ‘{0}你好,我是{1},我今年{2}岁了‘; var obj2 = ""; /* 对象:{ v1: ‘Cupid‘, v2: ‘Tina‘, v3: 18 } Json:{ "v1": "Cupid", "v2": "Tina", "v3": "18" } 注意:对象和JSON的区别 */ </script> </body> </html>
标签:
原文地址:http://www.cnblogs.com/alphafly/p/4681454.html