JS助手函数
注意: 函数非完全独立,函数内部或许使用到了其他函数。
补(填)0操作
function pad(val, len) {
val = String(val);
len = len || 2;
while (val.length < len) {
val = '0' + val;
}
return val;
}
深拷贝(克隆)函数
function deepCopy(data) {
const t = typeOf(data);
let o;
if (t === 'array') {
o = [];
} else if ( t === 'object') {
o = {};
} else {
return data;
}
if (t === 'array') {
for (let i = 0; i < data.length; i++) {
o.push(deepCopy(data[i]));
}
} else if ( t === 'object') {
for (let i in data) {
o[i] = deepCopy(data[i]);
}
}
return o;
}
递归获取对象的原型对象
function getPrototypeChain( obj ) {
let protoChain = [];
while (obj = Object.getPrototypeOf(obj) ) {
protoChain.push(obj)
}
protoChain.push(null); // 到达原型顶端null Object.prototype.__proto__ 值为null
return protoChain;
}
去除两边空格
function trim(string) {
const reg = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '');
};
-
\s:空格
-
\uFEFF:字节顺序标记字符(Byte Order Mark),也就是BOM,它是es5新增的空白符
-
\xA0:禁止自动换行空白符,相当于html中的
设置项目错误信息
function warnProp(component, prop, correctType, wrongType) {
correctType = firstUpperCase(correctType);
wrongType = firstUpperCase(wrongType);
console.error(`[Vue warn]: Invalid prop: type check failed for prop ${prop}. Expected ${correctType}, got ${wrongType}. (found in component: ${component})`); // eslint-disable-line
}
获取精确的数据类型
function typeOf(obj) {
const toString = Object.prototype.toString;
const map = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Undefined]': 'undefined',
'[object Null]' : 'null',
'[object Object]' : 'object'
};
return map[toString.call(obj)];
}
首字母大写
function firstUpperCase(str) {
return str.toString()[0].toUpperCase() + str.toString().slice(1);
}
找出数组重复的数
function findDulEle(arr){
var newArr = [];
var dupArr = [];
// 核心:
// 1. 创建一个新数组
// 2. 循环原数组的时候,判断新创建的数组中是否存在元素,存在则加入另外一个数组dupArr,否则push到新数组
arr.map(function(item){
if(!newArr.includes(item)){
// 不包含
newArr.push(item)
}else{
// 没有重复元素则加入到dupArr
if(dupArr.indexOf(item)== -1 ){
dupArr.push(item)
}
}
})
return dupArr;
}
var arr = [1,2,5,6,7,2,7,2]; // [2,7]
console.log( findDulEle(arr) )
生成随机字符串
function (len = 32) {
const $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
const maxPos = $chars.length;
let str = '';
for (let i = 0; i < len; i++) {
str += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return str;
}
判断参数是否是其中之一
export function oneOf (value, validList) {
for (let i = 0; i < validList.length; i++) {
if (value === validList[i]) {
return true;
}
return false;
}
}
驼峰连子符
function camelcaseToHyphen (str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
获取元素样式
function getStyle (element, styleName) {
if (!element || !styleName) return null;
styleName = camelCase(styleName);
if (styleName === 'float') {
styleName = 'cssFloat';
}
/*
let elem1 = document.getElementById("elemId");
let style = window.getComputedStyle(elem1, null);
// 它等价于
// let style = document.defaultView.getComputedStyle(elem1, null);
*/
try {
const computed = document.defaultView.getComputedStyle(element, '');
return element.style[styleName] || computed ? computed[styleName] : null;
} catch(e) {
return element.style[styleName];
}
}
获取url查询字符串
function searchParam(url) {
let search = location.search.slice(1) || '';
let params = {};
search && search.split('&').forEach(v => {
let [key, value] = v.split('=')
params[key] = decodeURIComponent(value)
})
return params;
}
let url = location.href;
console.log(searchParam(url));
生成唯一订单号
function genOrderId() {
var randomNumber = ""; //订单号
for (var i = 0; i < 6; i++) { //6位随机数,加在时间戳后面。
randomNumber += Math.floor(Math.random() * 10); // 20200304131312123412341212
}
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
// 补0操作 2021813
const formatNumber = n => {
n = n.toString()
// '8' => '08'
return n[1] ? n : '0' + n
}
return [year, month, day, hour, minute, second].map(formatNumber).join('') + randomNumber;
}
获取随机整数
function randomInt(min,max){
return parseInt(Math.random()*(max-min +1 )) + min;
}
递归获取对象的原型对象
function getPrototypeChain( obj ) {
let protoChain = [];
while (obj = Object.getPrototypeOf(obj) ) {
protoChain.push(obj)
}
protoChain.push(null); // 到达原型顶端null Object.prototype.__proto__ 值为null
return protoChain;
}
测试:
function Child(age,name) {
this.age = age;
this.name = name;
}
function Parent(info) {
this.info = info;
}
Parent.prototype.info = function () {
return this.info;
}
Child.prototype = new Parent('info');
Child.prototype.getName = function () {
return this.name;
}
Child.prototype.getAge = function () {
return this.age;
}
let p1 = new Child('kobe', '24');
console.log( getPrototypeChain(p1) );
结果:
(4) [Parent, {…}, {…}, null]
0: Parent {info: "info", getName: ƒ, getAge: ƒ}
1: {info: ƒ, constructor: ƒ}
2: {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
3: null
length: 4
__proto__: Array(0)