1. 简单的深拷贝
// 定义一个深拷贝函数 接收目标target参数
function deepClone(target) {
// 定义一个变量
let result;
// 如果当前需要深拷贝的是一个对象的话
if (typeof target === 'object') {
// 如果是一个数组的话
if (Array.isArray(target)) {
result = []; // 将result赋值为一个数组,并且执行遍历
for (let i in target) {
// 递归克隆数组中的每一项
result.push(deepClone(target[i]))
}
// 判断如果当前的值是null的话;直接赋值为null
} else if (target === null) {
result = null;
// 判断如果当前的值是一个RegExp对象的话,直接赋值
} else if (target.constructor === RegExp) {
result = target;
} else {
// 否则是普通对象,直接for in循环,递归赋值对象的所有值
result = {};
for (let i in target) {
result[i] = deepClone(target[i]);
}
}
// 如果不是对象的话,就是基本数据类型,那么直接赋值
} else {
result = target;
}
// 返回最终结果
return result;
}
let obj1 = {
name: 'name',
age: 'age',
aa: '',
bb: null,
cc: undefined
}
let ob2 = deepClone(obj1)
ob2.bb = 'xx1'
console.log(obj1)
console.log(ob2)
数组扁平化处理的办法
let arr = [
[1, 2],
[1, 2, 3],
[1, [1, 3, [1, 2, 3]]]
]
function flatten(arr) {
return arr.reduce((result, item) => {
return result.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
console.log(flatten(arr))
数的阶乘 使用while循环
function Add(num) {
let i = 1,
sum = 1;
while (i <= num) {
sum = sum * i;
i++
}
return sum
}
console.log(Add(5));