商品sku的排列组合

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>商品sku</title>
</head>

<body>
    <script>
        const names = ['iphoneX', 'iphoneXs'];
        const colors = ['黑色', '白色'];
        const sizes = ['64G', '128G'];
        // const res = [
        //     ['iphoneX', '黑色', '64G'],
        //     ['iphoneX', '黑色', '128G'],
        //     ['iphoneX', '白色', '64G'],
        //     ['iphoneX', '白色', '128G'],
        //     ['iphoneXs', '黑色', '64G'],
        //     ['iphoneXs', '黑色', '128G'],
        //     ['iphoneXs', '白色', '64G'],
        //     ['iphoneXs', '白色', '128G']
        // ]
        const all = [names, colors, sizes]
        let combine = function (all) {
            if (all.length < 2) {
                return all[0] || []
            }
            return all.reduce((pre, cur) => {
                let res = []
                pre.forEach(p => {
                    cur.forEach(c => {
                        let t = [].concat(Array.isArray(p) ? p : [p])
                        t.push(c)
                        res.push(t)
                    });
                });
                return res
            })
        }
        // let combine = function (all) {
        //     let res = []
        //     let fn = function (itemIndex, prev) {
        //         let item = all[itemIndex]
        //         let isLast = itemIndex === all.length - 1
        //         for (const val of item) {
        //             let cur = prev.concat(val)
        //             if (isLast) {
        //                 res.push(cur)
        //             } else {
        //                 fn(itemIndex + 1, cur)
        //             }
        //         }
        //     }
        //     fn(0, [])
        //     return res
        // }
        console.log(combine(all));

    </script>
</body>

</html>
posted @ 2020-07-02 11:02  Samsara315  阅读(529)  评论(0编辑  收藏  举报