<pre code_snippet_id="263631" snippet_file_name="blog_20140329_1_9913153" name="code" class="javascript">/字符串格式化 String.format('%s', arg)
String.format = function(src){
if (arguments.length == 0) return null;
var args = Array.prototype.slice.call(arguments, 1);
return src.replace(/\{(\d+)\}/g, function(m, i){
return args[i];
});
};
//获取url参数
function request(paras){
var url = location.href;
var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
var paraObj = {};
for (i=0; j=paraString[i]; i++){
paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
}
var returnValue = paraObj[paras.toLowerCase()];
if(typeof(returnValue)=="undefined"){
return "";
}else{
return unescape(returnValue);
}
}
//对js date 的扩展
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.format = function(fmt) {
//author: meizz
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr((""+ o[k]).length)));
return fmt;
};<pre name="code" class="javascript">//数组去重复
//说明 创建一个新的数组存放对象
//创建一个新对象
//for 循环的时候,每次取出一个元素与对象进行对比,如果元素不重复,则把它放到结果数组中,同时把这个元素的内容作为对象的一个属性,并
//赋值为1,存入到第2部建立的对象中
//说明:至于如何对比,就是每次从原数组中取出一个元素,然后到对象中去访问这个属性,如果能访问到值说明重复
Array.prototype.unique = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
};<pre name="code" class="javascript">//制保留2位小数,如:2,会在2后面补上00.即2.00
function toDecimal(x) {
var f = parseFloat(x);
if (isNaN(f)) {
return false;
}
var f = Math.round(x * 100) / 100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}
js 常用方法收集
最新推荐文章于 2024-03-29 02:06:48 发布