1
我试图映射具有n维子数组的数组。我看过深度地图,但我没有使用任何对象。什么我想要做的一个例子是:在deepMap数组在javascript中嵌套数组中映射非对象值
deepMap([4,5,[3,4,[2]]], (x) => x+5)
returns [9,10,[8,9,[7]]]
的功能后,可以是任何功能
const deepMap=(arr, fn) =>{
const stop = arr.length===0;
const tail = arr.slice(1);
const head = arr[0];
const front = head instanceof Array ? [head[0]]: [] ;
const next = fn(front, head);
return stop ? [] : front.concat(deepMap(tail,fn));
}
如何申请一个函数嵌套数组值,同时保持整个数组是嵌套数组?
任何帮助,非常感谢!
感谢Barmar!我试图不使用if语句,但是非常棒,帮助我可视化过程。我结束了这个: 'const deepMap =(arr,fn)=> const head = arr instanceof Array? arr.map((el)=> deepMap(el,fn)):fn(arr); 回头; (deepMap([4,5,[3,4,[2]]],(x)=> x + 5));'并且它正常工作 – Timmehlkk
您可以使用三元组代替: '返回arr instanceof数组? ...:...' – Barmar