Javascript函数不能正确展平数组

Javascript函数不能正确展平数组

问题描述:

我把一个JavaScript函数放在一起,这个函数应该是拼合一个嵌套数组。但是,这种方法总是只返回原始数组。例如,使用以下数组[1, 2, 3, [4, 5, [6], [ ] ] ]运行此函数将只返回该数组。我知道有些方法可以使用reduce来做到这一点,但是阻止这种方法工作的逻辑原因是什么? .map应该允许我操作一个返回值并通过递归调用返回新数组中的数据。Javascript函数不能正确展平数组

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

您正在使用地图。 Map返回一个'n'元素的数组。改用'.reduce'。 1简单的黑客可以是'var result = arr.toString()。split(',')' – Rajesh

+0

你只是将数组映射到自身,它只会返回自己。 – Li357

+0

它为什么将它映射到自己?它是递归调用函数,如果它是一个数组,应该只返回一个数字而不是数组。这样做的.reduce方法具有相同的递归调用。 .map应该允许你操作一个返回值并在新数组中返回。 – Dog

什么逻辑上的理由是防止这种方法从工作?

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) 

地图功能不发生变异原数组,但它会返回一个新的数组。

+0

不应该为每个工作,虽然? – Dog

+0

是的,这也将工作。除''reduce'外,'forEach','concat','spread operator'也将起作用 – brk

+0

forEach在上面的迭代中不起作用,但它只是在我将迭代设置为const并返回它时返回undefined – Dog

您正在将数组映射到它自己。基本上,因为map将返回一个数组,其元素数量与输入相同。你不能期望它返回更多,所以你不能用它来展平数组。

应该使用减少而不是:

function flatten(obj) { 

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

OP不在寻找替代品。他/她正在寻找解释*为什么地图不起作用* – Rajesh

+0

为什么三元操作中的递归调用不会返回一个数字而不是数组会是一个更准确的问题。 – Dog

+0

谢谢。我刚刚添加了原因 –