常用的前端 JavaScript 方法封装(下)
26、封装自己的filter方法
Array.prototype.myFilter = function (func, obj) {
var len = this.length;
var arr = [];
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this) && arr.push(this[i]);
}
return arr;
}
27、数组map方法
Array.prototype.myMap = function (func) {
var arr = [];
var len = this.length;
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
arr.push(func.call(_this, this[i], i, this));
}
return arr;
}
28、数组every方法
Array.prototype.myEvery = function (func) {
var flag = true;
var len = this.length;
var _this = arguments[1] || window;
for (var i = 0; i < len; i++) {
if (func.apply(_this, [this[i], i, this]) == false) {
flag = false;
break;
}
}
return flag;
}
29、数组reduce方法
Array.prototype.myReduce = function (func, initialValue) {
var len = this.length,
nextValue,
i;
if (!initialValue) {
// 没有传第二个参数
nextValue = this[0];
i = 1;
} else {
// 传了第二个参数
nextValue = initialValue;
i = 0;
}
for (; i < len; i++) {
nextValue = func(nextValue, this[i], i, this);
}
return nextValue;
}
30、获取url中的参数
function getWindonHref() {
var sHref = window.location.href;
var args = sHref.split('?');
if (args[0] === sHref) {
return '';
}
var hrefarr = args[1].split('#')[0].split('&');
var obj = {};
for (var i = 0; i < hrefarr.length; i++) {
hrefarr[i] = hrefarr[i].split('=');
obj[hrefarr[i][0]] = hrefarr[i][1];
}
return obj;
}
31、数组排序
// 快排 [left] + min + [right]
function quickArr(arr) {
if (arr.length <= 1) {
return arr;
}
var left = [],
right = [];
var pIndex = Math.floor(arr.length / 2);
var p = arr.splice(pIndex, 1)[0];
for (var i = 0; i < arr.length; i++) {
if (arr[i] <= p) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
// 递归
return quickArr(left).concat([p], quickArr(right));
}
// 冒泡
function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
function bubbleSort(arr) {
var len = arr.length;
for (var i = 0; i < len - 1; i++) {
for (var j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
32、遍历Dom树
// 给定页面上的DOM元素,将访问元素本身及其所有后代(不仅仅是它的直接子元素)
// 对于每个访问的元素,函数讲元素传递给提供的回调函数
function traverse(element, callback) {
callback(element);
var list = element.children;
for (var i = 0; i < list.length; i++) {
traverse(list[i], callback);
}
}
33、原生js封装ajax
function ajax(method, url, callback, data, flag) {
var xhr;
flag = flag || true;
method = method.toUpperCase();
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(2)
callback(xhr.responseText);
}
}
if (method == 'GET') {
var date = new Date(),
timer = date.getTime();
xhr.open('GET', url + '?' + data + '&timer' + timer, flag);
xhr.send()
} else if (method == 'POST') {
xhr.open('POST', url, flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
}
34、异步加载script
function loadScript(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // ie8及以下版本
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') {
callback();
}
}
} else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
35、cookie管理
var cookie = {
set: function (name, value, time) {
document.cookie = name + '=' + value + '; max-age=' + time;
return this;
},
remove: function (name) {
return this.setCookie(name, '', -1);
},
get: function (name, callback) {
var allCookieArr = document.cookie.split('; ');
for (var i = 0; i < allCookieArr.length; i++) {
var itemCookieArr = allCookieArr[i].split('=');
if (itemCookieArr[0] === name) {
return itemCookieArr[1]
}
}
return undefined;
}
}
36、实现bind()方法
Function.prototype.myBind = function (target) {
var target = target || window;
var _args1 = [].slice.call(arguments, 1);
var self = this;
var temp = function () {};
var F = function () {
var _args2 = [].slice.call(arguments, 0);
var parasArr = _args1.concat(_args2);
return self.apply(this instanceof temp ? this : target, parasArr)
}
temp.prototype = self.prototype;
F.prototype = new temp();
return F;
}
37、实现call()方法
Function.prototype.myCall = function () {
var ctx = arguments[0] || window;
ctx.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i])
}
var result = ctx.fn(...args);
delete ctx.fn;
return result;
}
38、实现apply()方法
Function.prototype.myApply = function () {
var ctx = arguments[0] || window;
ctx.fn = this;
if (!arguments[1]) {
var result = ctx.fn();
delete ctx.fn;
return result;
}
var result = ctx.fn(...arguments[1]);
delete ctx.fn;
return result;
}
39、防抖
function debounce(handle, delay) {
var timer = null;
return function () {
var _self = this,
_args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
handle.apply(_self, _args)
}, delay)
}
}
40、节流
function throttle(handler, wait) {
var lastTime = 0;
return function (e) {
var nowTime = new Date().getTime();
if (nowTime - lastTime > wait) {
handler.apply(this, arguments);
lastTime = nowTime;
}
}
}
41、requestAnimFrame兼容性方法
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
42、cancelAnimFrame兼容性方法
window.cancelAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
function (id) {
window.clearTimeout(id);
};
})();
43、jsonp底层方法
function jsonp(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // ie8及以下版本
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') {
callback();
}
}
} else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
44、获取url上的参数
function getUrlParam(sUrl, sKey) {
var result = {};
sUrl.replace(/(\w+)=(\w+)(?=[&|#])/g, function (ele, key, val) {
if (!result[key]) {
result[key] = val;
} else {
var temp = result[key];
result[key] = [].concat(temp, val);
}
})
if (!sKey) {
return result;
} else {
return result[sKey] || '';
}
}
45、格式化时间
function formatDate(t, str) {
var obj = {
yyyy: t.getFullYear(),
yy: ("" + t.getFullYear()).slice(-2),
M: t.getMonth() + 1,
MM: ("0" + (t.getMonth() + 1)).slice(-2),
d: t.getDate(),
dd: ("0" + t.getDate()).slice(-2),
H: t.getHours(),
HH: ("0" + t.getHours()).slice(-2),
h: t.getHours() % 12,
hh: ("0" + t.getHours() % 12).slice(-2),
m: t.getMinutes(),
mm: ("0" + t.getMinutes()).slice(-2),
s: t.getSeconds(),
ss: ("0" + t.getSeconds()).slice(-2),
w: ['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
};
return str.replace(/([a-z]+)/ig, function ($1) {
return obj[$1]
});
}
46、验证邮箱的正则表达式
function isAvailableEmail(sEmail) {
var reg = /^([\w+\.])+@\w+([.]\w+)+$/
return reg.test(sEmail)
}
47、函数柯里化
//是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术
function curryIt(fn) {
var length = fn.length,
args = [];
var result = function (arg) {
args.push(arg);
length--;
if (length <= 0) {
return fn.apply(this, args);
} else {
return result;
}
}
return result;
}
48、大数相加
function sumBigNumber(a, b) {
var res = '', //结果
temp = 0; //按位加的结果及进位
a = a.split('');
b = b.split('');
while (a.length || b.length || temp) {
//~~按位非 1.类型转换,转换成数字 2.~~undefined==0
temp += ~~a.pop() + ~~b.pop();
res = (temp % 10) + res;
temp = temp > 9;
}
return res.replace(/^0+/, '');
}
49、单例模式
function getSingle(func) {
var result;
return function () {
if (!result) {
result = new func(arguments);
}
return result;
}
}
评论