深拷贝函数

59 阅读2分钟

深拷贝函数

// 定义一个深拷贝函数  接收目标target参数 
export function deepClone(target: any) {
	// 定义一个变量
	let result: any;
	// 如果当前需要深拷贝的是一个对象的话
	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;
}

js实现数组扁平化的几种方式

//1、递归
var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr){
	let result = [];
	for(let i = 0; i < arr.length; i++) {
		if(Array.isArray(arr[i])){
			result = result.concat(flatDeep(arr[i]))
		} else {
			result.push(arr[i])
		}
	}
	return result;
}
console.log(flatDeep(array));

// 数组扁平化 children结构 [{id:'1',name:'一级',children:[{id:'1-1',name:'二级',children:null}]}]
export function flatDeep(arr: any) {
	let result: any[] = [];
	arr.forEach((item: { children: any }) => {
		result.push(item);
		if (item.children) {
			result = result.concat(flattenArray(item.children));
		}
	});
	return result;
}

方法二:用reduce函数

使用reduce方法累加效果,实现思路跟常规的递归方法有些相似

var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr){
	return arr.reduce(function(pre,next){
		if(Array.isArray(next)){
			return pre.concat(flatDeep(next))
		} else {
			return pre.concat(next)
		}
	}, [])
}
// 以上代码还可用三目运算符做如下简化
function flatDeep(arr) {
	return arr.reduce((pre, next) => {
		return pre.concat(Array.isArray(next) ?  flatDeep(next) : next)
	},[])
}
// 数组扁平化 children结构 [{id:'1',name:'一级',children:[{id:'1-1',name:'二级',children:null}]}]
function flatDeep(arr){
    return arr.reduce((pre, next) => {
            return pre.concat((next.children && Array.isArray(next.children)) ?  flatDeep(next.children) : next)
    },[])
}
console.log(flatDeep(array));
方法三:ES6的flat方法
  • flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。参数传进 Infinity 时,代表不论多少层都要展开。
var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr) {
	return arr.flat(Infinity)
}
console.log(flatDeep(array)); // [ 1, 2, 3, 4, 5 ]
方法四:扩展运算符与some函数结合
var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr) {
	while(arr.some(item => Array.isArray(item))){
		arr = [].concat(...arr)
	}
	return arr;
}
console.log(flatDeep(array)); // [ 1, 2, 3, 4, 5 ]