简体   繁体   English

展平JavaScript数组 - 为什么这不起作用?

[英]Flatten a JavaScript array — why isn't this working?

I'm trying to flatten an array with randomly nested arrays inside. 我试图用随机嵌套的数组来压扁数组。 I'm not sure why the function I wrote ends up in an infinite loop: 我不确定为什么我写的函数最终会在无限循环中结束:

let array = [1, 2, [3]]
var final_array = [] 

function flattener(array){
  for(i = 0; i < array.length; i++){
    if(array[i] instanceof Array){
      flattener(array[i])
    }else{
      final_array.push(array[i])
    }
  }
}

flattener(array)

What I think SHOULD happen is: 我认为应该发生的是:

When I'm in the for loop checking for [3] , it goes into the if statement, flattener gets called again, it resolves, and then I exit the if statement. 当我在for循环中检查[3] ,它会进入if语句,再次调用flattener ,它会解析,然后我退出if语句。

Instead, the if statement keeps calling to check [3] infinitely, and I'm not sure why this happens. 相反,if语句一直在无限地调用[3] ,我不确定为什么会这样。

The problem is you didn't declare the i variable, so it's leaking into the global space and being reset when it recurses. 问题是你没有声明i变量,所以它泄漏到全局空间并在recurses时被重置。

Change: 更改:

for(i = 0; i < array.length; i++){

To: 至:

for(var i = 0; i < array.length; i++){

This is another approach using Array.reduce and Array.concat . 这是使用Array.reduceArray.concat的另一种方法。

/**
 * Flattens an array of arrays into one-dimensional array
 * @param  {Array} arr: the array to be flattened
 * @return {Array}
 */
function flatten(arr) {
  return arr.reduce(function (flattened, cvalue) {
    return flattened.concat(Array.isArray(cvalue) ? flatten(cvalue) : cvalue);
  }, []); // initial value of flattened array []
}

Testing it... 测试它......

let array = [1, 2, [3]]
var falttened = flatten(array)

Take a look at his gist: Array flatten 看看他的要点: Array flatten

Array#concat plus Array#map is yet another way you can achieve this Array#concat plus Array#map另一种实现此目的的方法

var flattener = arr => [].concat.apply([], arr.map(item=>Array.isArray(item) ? flattener(item) : item));

or the ES5 version 或ES5版本

var flattener = function flattener(arr) {
  return [].concat.apply([], arr.map(function (item) {
    return Array.isArray(item) ? flattener(item) : item;
  }));
};

Change 更改

 for(i = 0; i < array.length; i++)

to

 for(var i = 0; i < array.length; i++)

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

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