首页 > 技术文章 > js一些方法的扩展

jiechen 2016-05-06 00:14 原文

  1 //JS扩展方法与C#的扩展方法非常相似,也是可以链式调用的,也是通过对某个类的扩展写法来实现。这个东西非常好用,如果将预先写好的方法放到一个js里面引用的话,那么后面写js将非常有趣。
  2 
  3 //下面给出一个例子:
  4 
  5 
  6 // <head>
  7 //     <title>测试JS扩展方法</title>
  8 //     <script type="text/javascript">
  9 //         // 合并多个空白为一个空白  
 10 //         String.prototype.ResetBlank = function() {        //对字符串扩展
 11 //             var regEx = /\s+/g;  
 12 //             return this.replace(regEx, ' ');  
 13 //         };  
 14 
 15 //         window.onload = function()
 16 //         {
 17 //             var str = "你      在他想还好吗?";
 18 //             alert(str);
 19 //             str = str.ResetBlank();        //这样就能够调用了,跟C#的很像吧!
 20 //             alert(str);
 21 //         }
 22 //     </script>
 23 // </head>
 24 
 25  // 好像只是告诉自己有这样一个东西而已;
 26 
 27  // 下面给出找到的一个非常不错的js扩展:
 28 
 29 // 清除两边的空格  
 30 String.prototype.trim = function() {  
 31     return this.replace(/(^\s*)|(\s*$)/g, '');  
 32 };  
 33 // 合并多个空白为一个空白  
 34 String.prototype.ResetBlank = function() {  
 35     var regEx = /\s+/g;  
 36     return this.replace(regEx, ' ');  
 37 };  
 38   
 39 // 保留数字  
 40 String.prototype.GetNum = function() {  
 41     var regEx = /[^\d]/g;  
 42     return this.replace(regEx, '');  
 43 };  
 44   
 45 // 保留中文  
 46 String.prototype.GetCN = function() {  
 47     var regEx = /[^\u4e00-\u9fa5\uf900-\ufa2d]/g;  
 48     return this.replace(regEx, '');  
 49 };  
 50   
 51 // String转化为Number  
 52 String.prototype.ToInt = function() {  
 53     return isNaN(parseInt(this)) ? this.toString() : parseInt(this);  
 54 };  
 55   
 56 // 得到字节长度  
 57 String.prototype.GetLen = function() {  
 58     var regEx = /^[\u4e00-\u9fa5\uf900-\ufa2d]+$/;  
 59     if (regEx.test(this)) {  
 60         return this.length * 2;  
 61     } else {  
 62         var oMatches = this.match(/[\x00-\xff]/g);  
 63         var oLength = this.length * 2 - oMatches.length;  
 64         return oLength;  
 65     }  
 66 };  
 67   
 68 // 获取文件全名  
 69 String.prototype.GetFileName = function() {  
 70     var regEx = /^.*\/([^\/\?]*).*$/;  
 71     return this.replace(regEx, '$1');  
 72 };  
 73   
 74 // 获取文件扩展名  
 75 String.prototype.GetExtensionName = function() {  
 76     var regEx = /^.*\/[^\/]*(\.[^\.\?]*).*$/;  
 77     return this.replace(regEx, '$1');  
 78 };  
 79   
 80 //替换所有
 81 String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
 82     if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
 83         return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);  
 84     } else {  
 85         return this.replace(reallyDo, replaceWith);  
 86     }  
 87 };  
 88 //格式化字符串  
 89 String.Format = function() {  
 90     if (arguments.length == 0) {  
 91         return '';  
 92     }  
 93   
 94     if (arguments.length == 1) {  
 95         return arguments[0];  
 96     }  
 97   
 98     var reg = /{(\d+)?}/g;  
 99     var args = arguments;  
100     var result = arguments[0].replace(reg, function($0, $1) {  
101         return args[parseInt($1) + 1];  
102     });  
103     return result;  
104 };  
105   
106 // 数字补零  
107 Number.prototype.LenWithZero = function(oCount) {  
108     var strText = this.toString();  
109     while (strText.length < oCount) {  
110         strText = '0' + strText;  
111     }  
112     return strText;  
113 };  
114   
115 // Unicode还原  
116 Number.prototype.ChrW = function() {  
117     return String.fromCharCode(this);  
118 };  
119   
120 // 数字数组由小到大排序  
121 Array.prototype.Min2Max = function() {  
122     var oValue;  
123     for (var i = 0; i < this.length; i++) {  
124         for (var j = 0; j <= i; j++) {  
125             if (this[i] < this[j]) {  
126                 oValue = this[i];  
127                 this[i] = this[j];  
128                 this[j] = oValue;  
129             }  
130         }  
131     }  
132     return this;  
133 };  
134   
135 // 数字数组由大到小排序  
136 Array.prototype.Max2Min = function() {  
137     var oValue;  
138     for (var i = 0; i < this.length; i++) {  
139         for (var j = 0; j <= i; j++) {  
140             if (this[i] > this[j]) {  
141                 oValue = this[i];  
142                 this[i] = this[j];  
143                 this[j] = oValue;  
144             }  
145         }  
146     }  
147     return this;  
148 };  
149   
150 // 获得数字数组中最大项  
151 Array.prototype.GetMax = function() {  
152     var oValue = 0;  
153     for (var i = 0; i < this.length; i++) {  
154         if (this[i] > oValue) {  
155             oValue = this[i];  
156         }  
157     }  
158     return oValue;  
159 };  
160   
161 // 获得数字数组中最小项  
162 Array.prototype.GetMin = function() {  
163     var oValue = 0;  
164     for (var i = 0; i < this.length; i++) {  
165         if (this[i] < oValue) {  
166             oValue = this[i];  
167         }  
168     }  
169     return oValue;  
170 };  
171   
172 // 获取当前时间的中文形式  
173 Date.prototype.GetCNDate = function() {  
174     var oDateText = '';  
175     oDateText += this.getFullYear().LenWithZero(4) + new Number(24180).ChrW();  
176     oDateText += this.getMonth().LenWithZero(2) + new Number(26376).ChrW();  
177     oDateText += this.getDate().LenWithZero(2) + new Number(26085).ChrW();  
178     oDateText += this.getHours().LenWithZero(2) + new Number(26102).ChrW();  
179     oDateText += this.getMinutes().LenWithZero(2) + new Number(20998).ChrW();  
180     oDateText += this.getSeconds().LenWithZero(2) + new Number(31186).ChrW();  
181     oDateText += new Number(32).ChrW() + new Number(32).ChrW() + new Number(26143).ChrW() + new Number(26399).ChrW() + new String('26085199682010819977222352011620845').substr(this.getDay() * 5, 5).ToInt().ChrW();  
182     return oDateText;  
183 };  
184 //扩展Date格式化  
185 Date.prototype.Format = function(format) {  
186     var o = {  
187         "M+": this.getMonth() + 1, //月份           
188         "d+": this.getDate(), //
189         "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
190         "H+": this.getHours(), //小时           
191         "m+": this.getMinutes(), //
192         "s+": this.getSeconds(), //
193         "q+": Math.floor((this.getMonth() + 3) / 3), //季度           
194         "S": this.getMilliseconds() //毫秒           
195     };  
196     var week = {  
197         "0": "\u65e5",  
198         "1": "\u4e00",  
199         "2": "\u4e8c",  
200         "3": "\u4e09",  
201         "4": "\u56db",  
202         "5": "\u4e94",  
203         "6": "\u516d"  
204     };  
205     if (/(y+)/.test(format)) {  
206         format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
207     }  
208     if (/(E+)/.test(format)) {  
209         format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);  
210     }  
211     for (var k in o) {  
212         if (new RegExp("(" + k + ")").test(format)) {  
213             format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
214         }  
215     }  
216     return format;  
217 }  
218 Date.prototype.Diff = function(interval, objDate) {  
219     //若参数不足或 objDate 不是日期类型則回传 undefined  
220     if (arguments.length < 2 || objDate.constructor != Date) { return undefined; }  
221     switch (interval) {  
222         //计算秒差                                                          
223         case 's': return parseInt((objDate - this) / 1000);  
224             //计算分差  
225         case 'n': return parseInt((objDate - this) / 60000);  
226             //计算時差  
227         case 'h': return parseInt((objDate - this) / 3600000);  
228             //计算日差  
229         case 'd': return parseInt((objDate - this) / 86400000);  
230             //计算周差  
231         case 'w': return parseInt((objDate - this) / (86400000 * 7));  
232             //计算月差  
233         case 'm': return (objDate.getMonth() + 1) + ((objDate.getFullYear() - this.getFullYear()) * 12) - (this.getMonth() + 1);  
234             //计算年差  
235         case 'y': return objDate.getFullYear() - this.getFullYear();  
236             //输入有误  
237         default: return undefined;  
238     }  
239 };  
240   
241 //检测是否为空  
242 Object.prototype.IsNullOrEmpty = function() {  
243     var obj = this;  
244     var flag = false;  
245     if (obj == null || obj == undefined || typeof (obj) == 'undefined' || obj == '') {  
246         flag = true;  
247     } else if (typeof (obj) == 'string') {  
248         obj = obj.trim();  
249         if (obj == '') {//为空  
250             flag = true;  
251         } else {//不为空  
252             obj = obj.toUpperCase();  
253             if (obj == 'NULL' || obj == 'UNDEFINED' || obj == '{}') {  
254                 flag = true;  
255             }  
256         }  
257     }  
258     else {  
259         flag = false;  
260     }  
261     return flag; 

 

推荐阅读