js 將多維數組轉爲一維數組:
var arr = [1,[2,[[3,4],5],6]];
function unid(arr){
var arr1 = (arr + '').split(',');
var arr2 = arr1.map(function(x){
return Number(x);
});
return arr2;
}
console.log(unid(arr));
複製代碼
防抖函數
tools.debounce = function (fn, delay = 300) {
let handle;
return function (e) {
clearTimeout(handle);
handle = setTimeout(() => {
fn(e);
}, delay);
}
}
複製代碼
經過toString方法獲取類型
tools.getType = (obj) => {
var type = '';
var typeArr = ['String', 'Object', 'Number', 'Array', 'Undefined', 'Function', 'Null', 'Symbol'];
for (var i = 0; i < typeArr.length; i++) {
if (Object.prototype.toString.call(obj) == '[object ' + typeArr[i] + ']') {
type = typeArr[i]
}
}
return type;
}
複製代碼
數據深拷貝
tools.deepCopy = (p, c) => {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
if (p[i] === null) {
c[i] = null;
} else {
c[i] = (p[i].constructor === Array) ? [] : {};
tools.deepCopy(p[i], c[i]);
}
} else {
c[i] = p[i];
}
}
return c;
}
複製代碼
設置本地存儲和本地讀取
tools.getStorage = key => {
const re = /^\[|\{|\}|\]$/g
let getIt = localStorage.getItem(key)
if (re.test(getIt)) {
return JSON.parse(getIt)
} else {
return getIt
}
}
tools.setStorage = (key, val) => {
if (typeof val == 'string') {
localStorage.setItem(key, val)
} else {
localStorage.setItem(key, JSON.stringify(val))
}
}
複製代碼
獲取多維數組的層級
function getArrTier(arr){
if (!Array.isArray(arr)) throw('type error')
let strArr = JSON.stringify(arr).split(']'),num = 0
for(let i = 0; i < strArr.length;i++){
let str2Arr = strArr[i].split('[')
if(num < str2Arr.length){
num = str2Arr.length
}
}
return num
}
複製代碼