简体   繁体   English

调用函数后如何重置全局变量?

[英]How can I reset the global variable after calling the function?

I've written a function with recursive approach to get the values from nested Array. 我用递归方法编写了一个函数,以从嵌套数组中获取值。 The problem is, I can't reset the global variable after each call. 问题是,每次调用后我都无法重置全局变量。 Here after every call the results are being appended to previous result instead of giving new result. 在此,每次调用后,结果都将附加到以前的结果中,而不是给出新的结果。 I know, Global variable isn't being reset, so data will always append. 我知道,全局变量不会被重置,因此数据将始终附加。 But I can't define the variable inside the function as its recursive call. 但是我不能将函数内部的变量定义为其递归调用。

How can I avoid this situation? 如何避免这种情况? Any help would be appreciated. 任何帮助,将不胜感激。

var res = [];
function getData(arr) {
  if(!Array.isArray(arr)) {
    res.push(arr);
    return res;
  }
  for(var i = 0; i < arr.length; i++) {
    getData(arr[i]);
  }
  return res;
}

getData([1, [2], [3, [[4]]]]); // res = [1, 2, 3, 4]
getData([[["a"]], [["b"]]]);   // res = [1, 2, 3, 4, "a", "b"], expected is res = ["a", "b"];
getData([1, {}, [3, [[4]]]]);

But I can't define the variable inside the function as its recursive call. 但是我不能将函数内部的变量定义为其递归调用。

You can define the result variable inside the function but you need to properly deal with the return values of your recursive calls: 您可以在函数内部定义result变量,但是您需要正确处理递归调用的返回值:

function getData(arr) {
    var res = [];

    if (Array.isArray(arr)) {
        for (var i = 0; i < arr.length; i++) {
            res = res.concat(getData(arr[i]));
        }
    } else {
        res.push(arr);
    }

    return res;
}

(And you don't need to make the result array a parameter of the function.) (并且您不需要使结果数组成为函数的参数。)

Landed up with another solution using closure, it might help someone. 找到另一个使用闭包的解决方案,它可能会对某人有所帮助。

function getData(arr) {
  var res = [];
  return innerGetData(arr);

  function innerGetData(arr) {
    if(!Array.isArray(arr)) {
      res.push(arr);
      return res;
    }
    for(var i = 0; i < arr.length; i++) {
      innerGetData(arr[i]);
    }
    return res;
  }
}

Hey a variant of the solution above is: 嘿,上述解决方案的一个变体是:

 function steamrollArray(arr) { var newArr = []; arr.forEach(function(el){ if(!Array.isArray(el)){ newArr.push(el); } else { newArr = newArr.concat(steamrollArray(el)); } }); return newArr; } 

:) :)

Use pop(array_name) to remove the last item from the array after you're done with it. 完成后,使用pop(array_name)从数组中删除最后一项。

-- Ada -艾达

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM