分类:
js
有很多时候,js不能像c#一样有那样多的方法操作,但是我们可以自己写一些方法,让他拥有:
比如最常见的一些:
注意:js里的注释最好用/**/,便于压缩
/*isNumber*/
/*功能:是否是数字*/
String.prototype.isNumber = function () {
return !isNaN(parseFloat(this)) && isFinite(this);
}
/*format*/
/*功能:你懂的*/
String.prototype.format = function () {
if (arguments.length == 0) return this;
for (var s = this, i = 0; i < arguments.length; i++)
s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
return s;
};
/*功能:去空格*/
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
/*获取路径参数*/
JSON.parseQueryString = function (url) {
var reg_url = /^[^\?]+\?([\w\W]+)$/,
reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
arr_url = reg_url.exec(url),
ret = {};
if (arr_url && arr_url[1]) {
var str_para = arr_url[1], result;
while ((result = reg_para.exec(str_para)) != null) {
ret[result[1]] = result[2];
}
}
return ret;
};
/*格式化金钱格式*/
Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "¥";
thousand = thousand || ",";
decimal = decimal || ".";
var number = this,
negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};
/*删除下标数组*/
Array.prototype.remove = function (dx) {
if (isNaN(dx) || dx > this.length) { return false; }
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[dx]) {
this[n++] = this[i]
}
}
this.length -= 1
};
/*无视大小写取值json对应值*/
var getKeyValue = function (obj, key, ignore) {
if (typeof (obj) != "object" || key==undefined) return;
if (ignore == undefined) ignore = true;
var _res = null;
$.each(obj, function (k, v) {
if (k != undefined && k != null&& k.toString().toLowerCase() == key.toLowerCase()) _res = v;
});
return _res;
};
//数组制定排序
Array.prototype.OrderByAsc = function (func) {
var m = {};
for (var i = 0; i < this.length; i++) {
for (var k = 0; k < this.length; k++) {
if (func(this[i]) < func(this[k])) {
m = this[k];
this[k] = this[i];
this[i] = m;
}
}
}
return this;
}
Array.prototype.OrderByDesc = function (func) {
var m = {};
for (var i = 0; i < this.length; i++) {
for (var k = 0; k < this.length; k++) {
if (func(this[i]) > func(this[k])) {
m = this[k];
this[k] = this[i];
this[i] = m;
}
}
}
return this;
}评价
