有点小九九
简单的事情认真做

常用于电商类项目(超浅显层面)

例如一种商品有三种规格:颜色,尺寸,种类

颜色又分为:[红,黄,蓝]

尺寸:[A,B]

种类:[1,2,3]

可以结合为多种排列

如:[‘红’,A,1],[‘黄’,A,1],....等,可以用到sku排列算法:

  摘抄的代码,原地址给忘了,

  

let arr = [
		    [1, 2, 3],
		    ['红', '黄', '蓝'],
		    ['A', 'B']
		];
		 
		function cartesianProductOf() {
		    return Array.prototype.reduce.call(arguments, (fristItem, secondItem) => {
		        var ret = [];
		        fristItem.forEach(function(fristItem) {
		            secondItem.forEach(function(secondItem) {
		                ret.push(fristItem.concat([secondItem]));
		            });
		        });
		        return ret;
		    }, [[]]);
		}
		 
		let allArr =cartesianProductOf(...arr )
		console.log(allArr)

  返回结果:

 1 (18) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
 2 0: (3) [1, "红", "A"]
 3 1: (3) [1, "红", "B"]
 4 2: (3) [1, "黄", "A"]
 5 3: (3) [1, "黄", "B"]
 6 4: (3) [1, "蓝", "A"]
 7 5: (3) [1, "蓝", "B"]
 8 6: (3) [2, "红", "A"]
 9 7: (3) [2, "红", "B"]
10 8: (3) [2, "黄", "A"]
11 9: (3) [2, "黄", "B"]
12 10: (3) [2, "蓝", "A"]
13 11: (3) [2, "蓝", "B"]
14 12: (3) [3, "红", "A"]
15 13: (3) [3, "红", "B"]
16 14: (3) [3, "黄", "A"]
17 15: (3) [3, "黄", "B"]
18 16: (3) [3, "蓝", "A"]
19 17: (3) [3, "蓝", "B"]
20 length: 18
21 __proto__: Array(0)

也可以简化一下:

 1 <script type="text/javascript">
 2         let arr = [
 3             [1, 2, 3],
 4             ['红', '黄', '蓝'],
 5             ['A', 'B']
 6         ];
 7         fn = (a, b) => [].concat(...a.map(d => b.map(e => [].concat(d, e))));
 8         specification = (a, b, ...c) => (b ? specification(fn(a, b), ...c) : a)
 9         let output = specification(...arr)
10         console.log(output)
11     </script>

结果和上面相同,记下来 慢慢学习规整

 

posted on 2020-09-22 18:02  有点小九九  阅读(1129)  评论(0编辑  收藏  举报