JS 常用方法封装
关于JS的一些总结, 持续更新中……
注:以下是一些常用方法封装,以备不时之需,当然 也可以直接使用 lodash,moment,dayjs 等等这种现成的包实现
1、输入一个值,返回其数据类型
function type(para) {
return Object.prototype.toString.call(para);
}
2、数组去重
function unique1(arr) {
return [...new Set(arr)];
}
function unique2(arr) {
let obj = {};
return arr.filter((ele) => {
if (!obj[ele]) {
obj[ele] = true;
return true;
}
});
}
function unique3(arr) {
let result = [];
arr.forEach((ele) => {
if (result.indexOf(ele) == -1) {
result.push(ele);
}
});
return result;
}
3、字符串去重
String.prototype.unique = function () {
let obj = {},
str = "",
len = this.length;
for (let i = 0; i < len; i++) {
if (!obj[this[i]]) {
str += this[i];
obj[this[i]] = true;
}
}
return str;
};
//去除连续的字符串
function uniq(str) {
return str.replace(/(\w)\1+/g, "$1");
}
4、深拷贝 浅拷贝
//深克隆(深克隆不考虑函数)
function deepClone(obj, result) {
let result = result || {};
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] == "object" && obj[prop] !== null) {
// 引用值(obj/array)且不为null
if (Object.prototype.toString.call(obj[prop]) == "[object Object]") {
// 对象
result[prop] = {};
} else {
// 数组
result[prop] = [];
}
deepClone(obj[prop], result[prop]);
} else {
// 原始值或func
result[prop] = obj[prop];
}
}
}
return result;
}
// 深浅克隆是针对引用值
function deepClone(target) {
if (typeof target !== "object") {
return target;
}
let result;
if (Object.prototype.toString.call(target) == "[object Array]") {
// 数组
result = [];
} else {
// 对象
result = {};
}
for (let prop in target) {
if (target.hasOwnProperty(prop)) {
result[prop] = deepClone(target[prop]);
}
}
return result;
}
// 无法复制函数
let o1 = jsON.parse(jsON.stringify(obj1));
5、reverse 底层原理和扩展
// 改变原数组
Array.prototype.myReverse = function () {
let len = this.length;
for (let i = 0; i < len; i++) {
let temp = this[i];
this[i] = this[len - 1 - i];
this[len - 1 - i] = temp;
}
return this;
};
6、圣杯模式的继承
function inherit(Target, Origin) {
function F() {}
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
// 最终的原型指向
Target.prop.uber = Origin.prototype;
}
7、找出字符串中第一次只出现一次的字母
String.prototype.firstAppear = function () {
let obj = {},
len = this.length;
for (let i = 0; i < len; i++) {
if (obj[this[i]]) {
obj[this[i]]++;
} else {
obj[this[i]] = 1;
}
}
for (let prop in obj) {
if (obj[prop] == 1) {
return prop;
}
}
};
8、找元素的第 n 级父元素
function parents(ele, n) {
while (ele && n) {
ele = ele.parentElement ? ele.parentElement : ele.parentNode;
n--;
}
return ele;
}
9、 返回元素的第 n 个兄弟节点
function retSibling(e, n) {
while (e && n) {
if (n > 0) {
if (e.nextElementSibling) {
e = e.nextElementSibling;
} else {
for (e = e.nextSibling; e && e.nodeType !== 1; e = e.nextSibling);
}
n--;
} else {
if (e.previousElementSibling) {
e = e.previousElementSibling;
} else {
for (
e = e.previousElementSibling;
e && e.nodeType !== 1;
e = e.previousElementSibling
);
}
n++;
}
}
return e;
}
10、封装 mychildren,解决浏览器的兼容问题
function myChildren(e) {
let children = e.childNodes,
arr = [],
len = children.length;
for (let i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
arr.push(children[i]);
}
}
return arr;
}
11、判断元素有没有子元素
function hasChildren(e) {
let children = e.childNodes,
len = children.length;
for (let i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
return true;
}
}
return false;
}
12、我一个元素插入到另一个元素的后面
Element.prototype.insertAfter = function (target, elen) {
let nextElen = elen.nextElenmentSibling;
if (nextElen == null) {
this.appendChild(target);
} else {
this.insertBefore(target, nextElen);
}
};
13、返回当前的时间(年月日时分秒)
function getDateTime() {
let date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() + 1,
minute = date.getMinutes(),
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return (
"" +
year +
"年" +
month +
"月" +
day +
"日" +
hour +
"时" +
minute +
"分" +
second +
"秒"
);
}
14、获得滚动条的滚动距离
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset,
};
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop,
};
}
}
15、获得视口的尺寸
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight,
};
} else {
// ie8及其以下
if (document.compatMode === "BackCompat") {
// 怪异模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight,
};
} else {
// 标准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight,
};
}
}
}
16、获取任一元素的任意属性
function getStyle(elem, prop) {
return window.getComputedStyle
? window.getComputedStyle(elem, null)[prop]
: elem.currentStyle[prop];
}