标签:style blog class code java c
1、格式化字符串操作
String.prototype.format = function(args) {
if (arguments.length>0) {
var result = this;
if (arguments.length == 1 && typeof (args) == "object") {
for (var key in args) {
var reg=new RegExp ("({"+key+"})","g");
result = result.replace(reg, args[key]);
}
}
else {
for (var i = 0; i < arguments.length; i++) {
if(arguments[i]==undefined)
{
return "";
}
else
{
var reg=new RegExp ("({["+i+"]})","g");
result = result.replace(reg, arguments[i]);
}
}
}
return result;
}
else {
return this;
}
}
两种调用方式,两个结果都是"我是loogn,今年22了"
var template1="我是{0},今年{1}了";
var template2="我是{name},今年{age}了";
var result1=template1.format("loogn",22);
var result2=template1.format({name:"loogn",age:22});
2、格式化字符串操作
$.format = function (source, params) {
if (arguments.length == 1)
return function () {
var args = $.makeArray(arguments);
args.unshift(source);
return $.format.apply(this, args);
};
if (arguments.length > 2 && params.constructor != Array) {
params = $.makeArray(arguments).slice(1);
}
if (params.constructor != Array) {
params = [params];
}
$.each(params, function (i, n) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
});
return source;
};
调用方法:$.format("I love {0}","u")
3、删除数组中指定位置的元素
Array.prototype.del = function (index) {
if (isNaN(index) || index >= this.length) {
return false;
}
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[index]) {
this[n++] = this[i];
}
}
this.length -= 1;
};
4、根据元素属性值删除数组中元素
/**
* 从对象数组中删除属性为objPropery,值为objValue元素的对象
* @param Array arrPerson 数组对象
* @param String objPropery 对象的属性
* @param String objPropery 对象的值
* @return Array 过滤后数组
*/
function Remove(arrayObj, objPropery, objValue) {
return $.grep(arrayObj, function (cur, i) {
return cur[objPropery] != objValue;
});
}
【Javascript】JS常用方法扩展,布布扣,bubuko.com
标签:style blog class code java c
原文地址:http://www.cnblogs.com/BruceGoGo/p/3721239.html