深度遍历数组

来源:互联网 发布:软件部门职责说明书 编辑:程序博客网 时间:2024/06/05 03:27

先说下解题思路:

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

基本数据类型: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,nullif(Object.prototype.toString.call(array[i])=="[object Array]"){  //数组 ArrymainFun(array[i]);}else if(Object.prototype.toString.call(array[i])=="[object Object]"){ //对象Objectfunction isObj(obj){   for(item in obj){  //item is key     if(typeof obj[item] =='object'){  //Object里的object,Array,nullif(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,Functionreset.push(obj[item]);}}}isObj(array[i]);}else{  //nullreset.push(array[i]);}}else{  //string,boolean,number,undefined,Functionreset.push(array[i]);}}}mainFun(list);return reset;}




原创粉丝点击