深度遍历数组

这篇博客探讨了在遍历数组时可能遇到的各种数据类型,包括基本类型和复杂类型如function、Object、Array。文章提到了使用typeof、instanceof以及Object.prototype.toString.call()来判断对象类型的方法,以解决遍历和类型识别的问题。作者提到,这些技巧适用于深度遍历,且该内容作为周末娱乐分享,欢迎大家指正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先说下解题思路:

第一:遍历数组可能遇到的数据有:

基本数据类型:string,number,boolean,null,undefined.

还有function , Object,Array

第二:首先想到的是使用typeOf,使用之后剩余的是null , Object,Array

第三:判断对象的属于哪一类可以使用instanceof,但是instanceof有一个缺陷,那就是原生构造函数要与对象在同一个全局作用域内。

第四:可以使用Object.prototype.toString.call()判断对象类型

这样就解决了所有的问题了,可以开始动工搬砖了,哈哈

纯属周末当娱乐写的,还有疏漏的欢迎指出,哈哈

function distinct(list){
	var list = list;
	var reset=[];
	function mainFun(array){   //将功能用函数封装
	  for(let i=0,len=array.length;i<len;i++){
	     if(typeof array[i] == 'object'){  //Object,Array,null
		if(Object.prototype.toString.call(array[i])=="[object Array]"){  //数组 Arry
			mainFun(array[i]);
		}else if(Object.prototype.toString.call(array[i])=="[object Object]"){ //对象Object
			function isObj(obj){
			   for(item in obj){  //item is key
			     if(typeof obj[item] =='object'){  //Object里的object,Array,null
				if(Object.prototype.toString.call(obj[item])=="[object Object]"){//子对象
					isObj(obj[item]);
		      }else if(Object.prototype.toString.call(obj[item])=="[object Array]"){										//子数组
									
				mainFun(obj[item]);
				}else{
				reset.push(obj[item]);//null
			}
			}else{  //string,boolean,number,undefined,Function
			reset.push(obj[item]);
			}
		}
	}
		isObj(array[i]);
	}else{  //null
		reset.push(array[i]);
	}				
	}else{  //string,boolean,number,undefined,Function				
		reset.push(array[i]);
	}
}
}
	mainFun(list);	
	return reset;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值