繁体   English   中英

Javascript函数无法正确展平数组

[英]Javascript Function Not Flattening Array Properly

我整理了一个JavaScript函数,该函数应该可以平铺嵌套数组。 但是,此方法始终只返回原始数组。 例如,使用以下数组[1, 2, 3, [4, 5, [6], [ ] ] ]运行此函数只会返回该数组。 我知道可以通过reduce来做到这一点,但是什么逻辑原因在阻止这种方法的工作呢? .map应该允许我操纵一个返回值,并通过递归调用在新数组中返回它。

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

您正在将数组映射到自身。 基本上是因为map将返回一个数组,该数组具有与输入完全相同的元素数。 您不能期望它返回更多,所以您不能使用它来展平数组。

应该使用reduce代替:

 function flatten(obj) {

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

是什么逻辑原因导致此方法无法正常工作?

 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函数不会更改原始数组,但会返回一个新数组。

暂无
暂无

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

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