Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - 递归遍历数组数组(Looping through array of Arrays with Recursion)

I am trying to solve this problem with recursion because I want to make my life worse.

(我想通过递归来解决此问题,因为我想让自己的生活变得更糟。)

I am taking an array of arrays and returning one array with all of the values.

(我正在使用一个数组数组,并返回一个包含所有值的数组。)

It is so close to working but the new array I am pushing to keeps reseting after every recursion.

(它是如此接近工作,但是我要推送的新数组在每次递归后都会不断重置。)

Can I get some advice?

(我可以得到一些建议吗?)

var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]

const flatten = function (arr) {
  let output = [];

  arr.map(element => {
    if (Array.isArray(element)) {
      console.log('Is Array ---> ', element)
      flatten(element);
    } else {
      console.log('Output ----->', output)
      console.log('Else     --->', element)
      output.push(element);
    }

  });

  return output;

};

console.log('Retrun ----->', flatten(myArray)); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
  ask by Jkaram translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should push the results of calling flatten(element) using the spread syntax :

(您应该使用传播语法推送调用flatten(element)的结果:)

output.push(...flatten(element));

Note: you should also replace the map call with Array.forEach() , since you don't use the returned array.

(注意:由于不使用返回的数组,因此还应该将映射调用替换为Array.forEach() 。)

Example:

(例:)

 const flatten = function(arr) { const output = []; arr.forEach(element => { if (Array.isArray(element)) { output.push(...flatten(element)); } else { output.push(element); } }); return output; }; var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]] console.log(flatten(myArray)); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...