题解 | #新数组#

新数组

https://www.nowcoder.com/practice/bee781a51bc944bbad20f3c2ca798890

 本题解题思路:需要先使用深拷贝将原有数组进行拷贝,否则无法处理引用类型的数据
 const _delete = (array,index) => {
 	let newArr=deepClone(array);
	newArr.splice(index,1);   
	return newArr;        
};            
function deepClone(source) {
	//先判断是否属于引用类型或者null   
	if (typeof source !== 'object' || source == null) { 
	return source;    
	}   
	//建立新的数组或者对象
	const target = Array.isArray(source) ? [] : {};
	for (const key in source) {
		//排除原型上的属性或者方法等
		if (Object.prototype.hasOwnProperty.call(source, key)) {
		//值类型为object,且属性值不为null的进行下一次递归
		if (typeof source[key] === 'object' && source[key] !== null) {
		target[key] = deepClone(source[key]);
		} else {
		//属性值为基本类型的则直接赋值
		target[key] = source[key];
		}
	}
	return target;
}

全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务