Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

这句代码意思

//多维转一维
    let arr = [
        [1],
        [2, 3],
        [4]
    ];
    const newArr = function(arr) {
        return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur), [])
    }
    console.log(newArr(arr)); //[1, 2, 3, 4]
    
    

return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur), [])这段代码啥意思求解答谢谢。。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const newArr = function(arr) {
    return arr.reduce((pre, cur) => {// 这是个箭头函数
        // 判断cur 是否为数组:是数组则 newArr(cur) 递归调用
        // 一直到cur不是数组了,则赋值给tmp
        let tmp = Array.isArray(cur) ? newArr(cur) : cur;
        // 把tmp和pre拼接起来,作为返回值
        return pre.concat(tmp);
    }, [])
}

reduce遍历数组

[1,2,3].reduce(callback, initValue);
[1,2,3].reduce((pre, current, index, array)=>{
    console.log(pre, current, index, array);
}, 0);

这里有reduce的其他应用,可以参考下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...