JS数组串联以实现递归展平的结果 [英] JS array concatenation for results of recursive flattening

查看:60
本文介绍了JS数组串联以实现递归展平的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!

任务是获取数组的平面版本,其中可能包括一定数量的嵌套数组以及其他元素.对于输入 [1,[2],[3,[[4]]] ,预期输出 [1、2、3、4] . FreeCodeCamp扰流板警报.自然会想到递归解决方案,例如:

Task would be to get a flat version of an array, that may include some amount of nested arrays as well as other elements. For input [1, [2], [3, [[4]]]] output [1, 2, 3, 4] expected. FreeCodeCamp spoiler alert. Naturally, recursive solution comes to mind, e.g.:

function steamrollArray(arr) {
  var result = [];
  for(var i = 0; i < arr.length; i++){
      //part of interest
      if (Array.isArray(arr[i])){
        var nestedElements = steamrollArray(arr[i]);
        for(var j = 0; j < nestedElements.length; j ++){
          result.push(nestedElements[j]);
        }
      //</part of interest>.
      } else {
        console.log("pushing: " + arr[i]);
        result.push(arr[i]);
      }
  }
  return result;
}

做到了.样品运行的结果将是:

And it does it's thing. Result of sample run would be:

pushing: 1
pushing: 2
pushing: 3
pushing: 4
[1, 2, 3, 4]

问题是:当我们使用concat添加 nestedElements (应该存储递归调用的返回结果)时,哪里出错了.如果要更改 for 循环中的第一个 if {} 块(标记为感兴趣的一部分),请使用以下代码段:

And the question is: what goes awry, when we use concat to add nestedElements (that supposedly store return result of recursive call). If we are to change first if{} block in for loop (marked as part of interest) with snippet below:

if (Array.isArray(arr[i])){
    var nestedElements = steamrollArray(arr[i]);
    result.concat(nestedElements);
} else {

我们将观察到以下结果:

we will observe the following result:

pushing: 1
pushing: 2
pushing: 3
pushing: 4
[1]

我的理解是将每个递归调用的结果传递给 concat 函数,该函数会将返回的数组添加到结果中,但是由于某种原因,情况并非如此.有人问了关于此任务的问题,例如这个问题,但是那些与之相关的问题与展平算法部分,这里不作质疑.我仍然看不到答案到底是什么引起了差异.这很可能是我只是出于麻烦或由于我有限的经验而忽略了的事情.抱歉,是这样的.

My understanding was to pass the result of each recursive call to the concat function, which will add the returned array to the result, but for some reason it's not the case. Questions on this task was asked, like this one, but those concerned with the flattening algorithm part, which is not questioned here. I still fail to see the answer what exactly causes the difference. It very well might be something I simply overlooked in a hassle or as a result of my limited experience. Sorry if that's the case.

推荐答案

Array#concat 返回带有结果的新数组.

Array#concat returns a new array with the result.

concat() 方法将返回一个新数组,该数组由调用该数组的数组以及提供的数组和/或值组成作为参数.

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

所以您需要分配结果:

result = result.concat(nestedElements);
// ^^^^^^ assignment

这篇关于JS数组串联以实现递归展平的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆