1. 深拷贝
let arr = [1, [{name: '张三'}, [18, 22], undefined], null, 'hello']
function deepClone(target) {
let result;
if (typeof target === 'object') {
if (Array.isArray(target)) {
result = []
for (let i in target) {
// 递归克隆数组中的每一项
result.push(deepClone(target[i]))
}
} else if (target === null) { // null的情况
result = target
} else if (target.constructor === RegExp) { // 正则的情况
result = target
} else {
result = {}
for (let key in target) {
result[key] = deepClone(target[key])
}
}
} else {
result = target
}
return result
}
console.log(deepClone(arr))
2. 数组降维(扁平化数据)
function flatAll(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result = result.concat(arguments.callee(item)) // arguments.callee递归
} else {
result.push(item)
}
})
return result
}
console.log(flatAll([1,[2,2,[3,3,[4,4,[5,5,[6,6,[7,7]]]]]]]));
// [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]
3. 柯里化 add(1)(2)(3)
const curry = (fn, ...args) => {
// 函数的参数个数可以直接通过函数数的.length属性来访问
// 传入的参数大于等于原始函数fn的参数个数,则直接执行该函数
return args.length >= fn.length
? fn(...args) :
/**
* 传入的参数小于原始函数fn的参数个数时
* 则继续对当前函数进行柯里化,返回一个接受所有参数(当前参数和剩余参数)
* 的函数
*/
(..._args) => curry(fn, ...args, ..._args)
}
function add1 (a, b, c) {
return a + b + c
}
const add = curry(add1)
console.log(add(1)(2)(3)) // 6
console.log(add(1, 2)(3)) // 6