版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z772532526/article/details/82722097
一、简易元素选择器( id, class, tag )
//用法大致同jQuery相同,第二个参数为上下文。
window.$ = function(selector,context){
context = context || document;
let NodeList = context.querySelectorAll(selector);
return selector.charAt(0) === '#' ? NodeList[0] : NodeList;
}
二、获取元素的现有样式
HTMLElement.prototype.getStyle = function(key){
return window.getComputedStyle(this,null)[key];
}
简单地仿PHP date()方法,返回特定格式的日期和时间。
window.date = function(format = 'Y-m-d H:i:s',timestamp = false){
let now = new Date();
if(timestamp){
if(timestamp.toString().length === 13){
now.setTime(timestamp);
}else{
console.log('时间戳应该为毫秒');
return false;
}
}
let str = '',i = 0,w;
while(w = format.charAt(i++)){
switch(w){
case 'Y':
str += now.getFullYear();
break;
case 'm':
str += pad0(now.getMonth() + 1);
break;
case 'd':
str += pad0(now.getDate());
break;
case 'H':
str += pad0(now.getHours());
break;
case 'i':
str += pad0(now.getMinutes());
break;
case 's':
str += pad0(now.getSeconds());
break;
default:
str += w;
}
}
return str;
}
function pad0(value){
return value > 9 ? value : '0' + value;
}
删除数组中指定的值
Array.prototype.deleteValue = function(value){
let index = this.indexOf(value);
return index > -1 ? this.splice(index,1) : false;
}
数组去重两个方法
Array.prototype.unique1 = function(){
let arr = [],obj = {};
for (let i of this) {
if(obj[i] === undefined){
arr.push(i);
obj[i] = true;
}
}
return arr;
}
Array.prototype.unique2 = function(){
return Array.from(new Set(this));
}
类型转换
//对象键名转数组
Object.keys(obj);
//对象键值专属组
Object.values(obj);
//对象转JSON
JSON.stringify(obj);
//JSON转对象
JSON.parse(str);
//Set转数组
Array.from(set);