DFS如何在javascript中的嵌套数组上工作

时间:2019-03-20 21:47:18

标签: javascript arrays depth-first-search

有人可以解释一下DFS如何在嵌套数组上工作。 我指的是所有Wiki和stackover的资源,但我不太了解如何使用DFS在arry上进行递归搜索,请将其视为我的数组:

array = ["abc","abc2","abc22"];
array[0] = ["test","test1","test2"];
array[0][0] = ["22","33","333"];
array[0][1] = ["we","we2","we3"];
array[0][1][2] = ["soon","soon2","soon3"];
array[1] = ["get"];
array[1][0] ="get2";
array[2] = ["set","set2","set3"];
array[2][0] = "ready";
array[2][1] = ["123","334"];
array[2][2] ="cry";

https://jsfiddle.net/fmbw0eth/7/

我们如何遍历数组中的每个元素及其子数组,依此类推。 到目前为止,我已经知道了:

array.map(function(n,i){
  if (Array.isArray(n)) {
  n.map(function(n,i){
   // and keep checking for arrays and when reached at the bottom ,
   // somefunction(n);
})
}else {
someFucntion(n);
}

})

这是DFS的正确方法,还是有更好的递归方式遍历数组?

1 个答案:

答案 0 :(得分:0)

DFS用于图形或树。您正在使用的是一个数组。如果要访问所有可能的嵌套数组及其索引,则可以使用递归来遍历数组元素。

var array;
array = ["abc","abc2","abc22"];
array[0] = ["test","test1","test2"];
array[0][0] = ["22","33","333"];
array[0][1] = ["we","we2","we3"];
array[0][1][2] = ["soon","soon2","soon3"];
array[1] = ["get"];
array[1][0] ="get2";
array[2] = ["set","set2","set3"];
array[2][0] = "ready";
array[2][1] = ["123","334"];
array[2][2] ="cry";

function getAllNestedElements(arr) {
	var result = [];
    for(var i=0; i<arr.length; i++) {
    	if (Array.isArray(arr[i])) {
        	result = result.concat(getAllNestedElements(arr[i]));
        }
        else {
        	result.push(arr[i]);
       	}
    }
    //console.log(result);
    return result;
}

console.log(getAllNestedElements(array));