Javascript 嵌套数组中的运算

Javascript 嵌套数组中的运算,javascript,ecmascript-6,Javascript,Ecmascript 6,我有一个嵌套数组,如下所示 var x=[1,2,[3,4,[5,6,[7,8,[9,10]]]]] [2,4,[6,8,[10,12,[14,16,[18,20]]]]] function nestedArrayOperation(arr){ var p=[]; arr.forEach(function(item,index){ if(Array.isArray(item)){ p.push(nestedArrayOperation(

我有一个嵌套数组,如下所示

var x=[1,2,[3,4,[5,6,[7,8,[9,10]]]]]
[2,4,[6,8,[10,12,[14,16,[18,20]]]]]
function nestedArrayOperation(arr){
    var p=[];
    arr.forEach(function(item,index){
        if(Array.isArray(item)){
            p.push(nestedArrayOperation(item))
            return
        }
        p.push(item*2);//multiply by 2
        return 
    });
    return p;
}
我想在数组中执行一些运算,假设每个元素与2相乘,结果如下

var x=[1,2,[3,4,[5,6,[7,8,[9,10]]]]]
[2,4,[6,8,[10,12,[14,16,[18,20]]]]]
function nestedArrayOperation(arr){
    var p=[];
    arr.forEach(function(item,index){
        if(Array.isArray(item)){
            p.push(nestedArrayOperation(item))
            return
        }
        p.push(item*2);//multiply by 2
        return 
    });
    return p;
}
到目前为止,我已经做了如下工作

var x=[1,2,[3,4,[5,6,[7,8,[9,10]]]]]
[2,4,[6,8,[10,12,[14,16,[18,20]]]]]
function nestedArrayOperation(arr){
    var p=[];
    arr.forEach(function(item,index){
        if(Array.isArray(item)){
            p.push(nestedArrayOperation(item))
            return
        }
        p.push(item*2);//multiply by 2
        return 
    });
    return p;
}
函数嵌套ArrayOperation(arr){
var p=[];
arr.forEach(功能(项目、索引){
if(阵列isArray(项目)){
p、 推送(嵌套阵列操作(项目))
返回
}
p、 推(项*2);//乘以2
返回
});
返回p;
}
变量x=[1,2,3,4,5,6,7,8,9,10]]
console.log(nestedArrayOperation(x))

。作为控制台行代码{white space:nowrap!important;}
您可以使用一个回调来检查值并映射数组或乘法值

此建议使用并返回一个新数组

var times2=v=>Array.isArray(v)?v、 地图(时间2):2*v,
x=[1,2,3,4,5,6,7,8,9,10],
x2=x.map(时间2);
控制台日志(x2)
.as控制台包装{max height:100%!重要;top:0;}
您正在寻找的

函数嵌套ArrayOperation(arr,回调){
返回arr.map(函数(项、索引){
if(阵列isArray(项目))
返回NestedarayOperation(项,回调);
其他的
返回回调(项、索引);
});
}
var示例=[1,2,3,4,5,6,7,8,9,10];
log(nestedArrayOperation(例如,x=>x*2))
  • 将回调函数作为原型函数的参数传递
  • 然后通过递归函数调用传递
  • 对于更简单的形式,请使用
    数组中的
    三元运算符
    #map
  • Array.prototype.nestedArrayOperation=函数(回调){
    返回此.map((项,索引)=>Array.isArray(项)?item.nestedArrayOperation(回调):回调(项));
    }
    变量x=[1,2,3,4,5,6,7,8,9,10]]
    console.log(x.nestedArrayOperation((x)=>x+2))
    console.log(x.nestedArrayOperation((x)=>x*2))
    。作为控制台行代码{
    空白区:nowrap!重要;
    
    }
    你的意思是?我知道,但它会像地图和地图一样function@SourabhSomani像map和reduce函数一样,你能更具体一点吗?我可以使用
    array.prototype
    添加数组函数,但我想让它成为通用的意思是
    x+5
    x+3
    或我的任何操作can@SourabhSomani你是否期望这个函数要处理的递归部分?