lodash.get(obj, path, default)
function _get(obj, path, defaultValue) {
// 匹配[]""''.这几个字符之外的任意字符 例如a[0].b.c匹配后 返回[ 'a', '0', 'b', 'c' ]
const result = path.match(/[^\[\]""''.]+/g).filter(Boolean)
.reduce((o, k) => o === undefined ? o : o[k], obj);
return result === undefined ? defaultValue : result;
}
// 使用示例
const obj = { a: [{ b: { c: 3 } }] };
console.log(_get(obj, 'a[0].b.c', 'default')); // 输出: 3
console.log(_get(obj, 'a[0].b.d', 'default')); // 输出: 'default'
console.log(_get(obj, 'a[0]["b"]["c"]', 'default')); // 输出: 3
deepClone
function deepClone(startObj) {
const obj = Array.isArray(startObj) ? [] : {}
for (let key in startObj) {
if (typeof startObj[key] === 'object') {
obj[key] = deepClone(startObj[key])
} else {
obj[key] = startObj[key]
}
}
return obj
}
function test() {
const a = {
b : { c: 1},
d : [1, 2]
}
const b = [1, 2, a ]
console.log(deepClone(a), deepClone(b))
}
debounce,throllte
/ 单位时间内频繁触发一个事件,以最后一次触发为准
function debounce(func, delay) {
let timer
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
func.call(this)
}, delay)
}
}
// 单位时间内频繁触发一个事件,只触发一次
function throllte(func, delay) {
let timer
return function() {
if (timer) return
timer = setTimeout(() => {
func.call(this)
timer = null
}, delay)
}
}