1.url序列化为json
function serilizeUrl(url) {
var urlObject = {};
if (/\?/.test(url)) {
var urlString = url.substring(url.indexOf("?") + 1);
var urlArray = urlString.split("&");
for (var i = 0, len = urlArray.length; i < len; i++) {
var urlItem = urlArray[i];
var item = urlItem.split("=");
urlObject[item[0]] = item[1];
}
return urlObject;
}
return null;
}
2.从url取值
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null) return unescape(r[2]);
return null; //返回参数值
}
3.两种阶乘方法
function hi(n){
var prd = 1;
for(var i=1;i<=n;i++){
prd*=i;
}
return prd;
}
function li(n){
if(n<2){
return 1;
}else{
for(var i=0;i<n;i++){
return n*arguments.callee(n-1);
}
}
}
4.jsonp拿豆瓣电影信息
function jsonp(url, data, callback) {
var suffix = Math.random().toString().replace('.', ''),
cbName = 'my_cb' + suffix,
queryStr = url.indexOf('?') == -1 ? '?' : '&';
for (var key in data) {
queryStr += key + '=' + data[key] + '&';
};
queryStr += 'callback' + '=' + cbName;
window[cbName] = function(shuju) {
callback(shuju);
//把script请求回来的函数挂在window上,执行完成后再remove,防止一个页生成很多script标签
document.body.removeChild(newScriptEle);
};
var newScriptEle = document.createElement("script");
newScriptEle.src = url + queryStr;
document.body.appendChild(newScriptEle);
};
var url = 'http://api.douban.com/v2/movie/coming_soon',
data = { start: 0, count: 5 };
jsonp(url, data, function(data) {
console.log(data)
});
5.数组去重
方法1:
function delRepeat(arr){
var result = [];
for(var i=0; i<arr.length; i++){
if(result.indexOf(arr[i]) == -1){
result.push(arr[i]);
}
}
return result;
};
方法2:
arr.filter(function(ele, index, array){
return index===array.indexOf(ele)
});
方法3:
//利用的是js对象不能重复的特性
let arr = [1,3,4,5,7,9,2,3,4,7,9];
function toObject(arr){
var obj = {};
for (var item of arr){
obj[item] = 1;
}
return obj;
};
function toArray(obj){
var array = [];
for (var attr in obj){
array.push(attr);
}
return array;
}
let Object = toObject(arr);
let result = toArray(Object);
console.log(result);
6.数组求最大值最小值
最大值:
function maxArr(arr) {
return Math.max.apply(null, arr)
}
最小值:
function minArr(arr) {
return Math.min.apply(null, arr)
}
7.数字转成货币大写
第一种:
function digitUppercase(n) {
var fraction = ['角', '分'];
var digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
var unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
var head = n < 0 ? '欠' : '';
n = Math.abs(n);
var s = '';
for (var i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (var i = 0; i < unit[0].length && n > 0; i++) {
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
}
第二种:
function DX(n) {
if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return "数据非法";
var unit = "京亿万仟佰拾兆万仟佰拾亿仟佰拾万仟佰拾元角分",
str = "";
n += "00";
var p = n.indexOf(".");
if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2);
unit = unit.substr(unit.length - n.length);
for (var i = 0; i < n.length; i++)
str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);
return str
.replace(/零(仟|佰|拾|角)/g, "零")
.replace(/(零)+/g, "零")
.replace(/零(兆|万|亿|元)/g, "$1")
.replace(/(兆|亿)万/g, "$1")
.replace(/(京|兆)亿/g, "$1")
.replace(/(京)兆/g, "$1")
.replace(/(京|兆|亿|仟|佰|拾)(万?)(.)仟/g, "$1$2零$3仟")
.replace(/^元零?|零分/g, "")
.replace(/(元|角)$/g, "$1整");
}
8.过去时间戳距今时长格式化
function formatPassTime(startTime) {
var currentTime = Date.parse(new Date()),
time = currentTime - startTime,
day = parseInt(time / (1000 * 60 * 60 * 24)),
hour = parseInt(time / (1000 * 60 * 60)),
min = parseInt(time / (1000 * 60)),
month = parseInt(day / 30),
year = parseInt(month / 12);
if (year) return year + "年前"
if (month) return month + "个月前"
if (day) return day + "天前"
if (hour) return hour + "小时前"
if (min) return min + "分钟前"
else return '刚刚'
};
var nowTimestamp = new Date().getTime();
console.log(formatPassTime(nowTimestamp));//刚刚
9.未来时间倒计时
function formatRemainTime(endTime) {
var startDate = new Date(); //开始时间
var endDate = new Date(endTime); //结束时间
var t = endDate.getTime() - startDate.getTime(); //时间差
var d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
return d + "天 " + h + "小时 " + m + "分钟 " + s + "秒";
};
var et = '2018-01-06';
setInterval(function(){
console.log(formatRemainTime(et))
},1000)
10.随机获取数组的一员
function randomOne(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
11.对象深拷贝
JSON.parse(JSON.stringify(obj))
12.toLocalString的高级用法
(123456789).toLocaleString('zh-hans-CN-u-nu-hanidec',{useGrouping:false})
"一二三四五六七八九"
(123456789).toLocaleString('zh-hans-CN-u-nu-hanidec',{useGrouping:true})
"一二三,四五六,七八九"
new Date().toLocaleString('zh-hans-CN-u-nu-hanidec')
"二〇一八/一/二五 下午六:二七:二三"