简体   繁体   English

Javascript函数无法正确展平数组

[英]Javascript Function Not Flattening Array Properly

I put together a JavaScript function that is supposed to flatten a nested array. 我整理了一个JavaScript函数,该函数应该可以平铺嵌套数组。 However, this method always just returns the original array. 但是,此方法始终只返回原始数组。 For example, running this function with the following array [1, 2, 3, [4, 5, [6], [ ] ] ] will just return that array. 例如,使用以下数组[1, 2, 3, [4, 5, [6], [ ] ] ]运行此函数只会返回该数组。 I know there are ways to do this with reduce, but what logical reason is preventing this method from working? 我知道可以通过reduce来做到这一点,但是什么逻辑原因在阻止这种方法的工作呢? .map should allow me to manipulate a return value and return that within the new array through the recursion call. .map应该允许我操纵一个返回值,并通过递归调用在新数组中返回它。

function mapper(array) { 
    return array.map((item) => {
        return (Array.isArray(item)) ? mapper(item) : item
    } 
)}

You are mapping the array to itself. 您正在将数组映射到自身。 Basically because map will return an array with exact same number of elements as the input. 基本上是因为map将返回一个数组,该数组具有与输入完全相同的元素数。 You cant expect it to return more, so you cant use it for flattening the array. 您不能期望它返回更多,所以您不能使用它来展平数组。

Should use reduce instead: 应该使用reduce代替:

 function flatten(obj) {

     if (Array.isArray(obj)) {
          return obj.reduce((a, b) => a.concat(flatten(b)), []);
     } else {
          return [obj];
     }
 }

what logical reason is preventing this method from working? 是什么逻辑原因导致此方法无法正常工作?

 var m = [1, 2, 3, [4, 5, [6], []]];
 function mapper(array) { 
        return array.map((item) => {
            // for 1,2,3 it will return item
            // when it sees an array it will again call mapper & map
            // function will return a new array from it, so map on 
            // [4, 5, [6], []] will return a new array but will not take out
            // individual element and will put it in previous array

            return (Array.isArray(item)) ? mapper(item) : item
        } 
    )}
mapper(m)

map function does not mutate the original array but it will return a new array. map函数不会更改原始数组,但会返回一个新数组。

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

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