实现36进制
function num36() {
var arr = []
for (let i = 0; i < 36; i++) {
if (i < 10) {
arr.push(i)
} else {
arr.push(String.fromCharCode(i + 87))
}
}
return arr;
}
function trans36(n) {
var arr = []
var get36 = num36()
while(n) {
var res = n % 36;
arr.unshift(get36[res])
n = parseInt(n / 36)
}
return arr.join('')
}
手写new
function New(fn, ...args) {
let obj = Object.create(fn.prototype);
let res = fn.apply(obj, args)
return typeof res === 'object' ? res : obj
}
bind
if (!Function.prototype.bind) {
Function.prototype.bind = function() {
let that = this
let [ctx, ...args] = arguments
return function() {
that.apply(ctx, args.concat([].slice.apply(arguments)))
}
}
}
apply
if (!Function.prototype.apply) {
Function.prototype.apply = function() {
let [ctx, args] = arguments
ctx.fn = this || window
let res = ctx.fn(...args)
delete ctx.fn
return res
}
}
call
if (!Function.prototype.call) {
let [ctx, ...args] = arguments
ctx.fn = this || window
let res = ctx.fn(...args)
delete ctx.fn
return res
}
深复制
function deepObj(obj) {
let newObj = {}
Object.keys(obj).forEach((item, index) => {
if (typeof obj[item] === 'object') {
newObj[item] = deepObj(obj[item])
} else {
newObj[item] = obj[item]
}
})
return newObj;
}
cookie
设置(存储object时需JSON.stringify 取出时需JSON.parse)
function setCookie(key, val, day) {
let str = `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
if (day) {
let date = new Date()
date.setTime(date.getTime() + (day*24*60*60*1000))
str += `; expires=${date.toGMTString()}`
}
document.cookie = str;
}
function getCookie(name) {
let arr = document.cookie.split('; ');
let str = ``
arr.every((item, index) => {
let diff = name + '=';
if (item.indexOf(diff) === 0) {
str = decodeURIComponent(item.replace(diff, ''))
return false
} else {
return true
}
})
return str
}
扁平化
1. 直接处理
[1,2,[3,4],[6,7,8,9]].flat()
2. String
String([1,2,[3,4],[6,7,8,9]]).split(',')
3. JSON.stringify
JSON.stringify([1,2,[3,4],[6,7,8,9]]).replace(/(\[|\])/g, '').split(',')
4. reduce
[1,2,[3,4],[6,7,8,9]].reduce((before, second) => {
return before.concat(second)
}, [])
5. ...扩展运算符
[].concat(...[1,2,[3,4],[6,7,8,9]])
6. 递归
function flat(arr) {
let newArr = []
for (let i=0; i<arr.length; i++) {
if (Array.isArray(arr[i])) {
let res = flat(arr[i])
newArr.push(...res)
} else {
newArr.push(arr[i])
}
}
return newArr
}