最近在做ali项目,设计到类似淘宝、ebay的sku的算法,比如说某种商品有N(用未知数N来表示是因为规格的数组由用户制定且随时可以编辑的,所以对程序来说,它是一个未知数)类规格,每一类规格又有M个规格值,各种规格值的组合便是一个型号,比如说,颜色是商品规格的一类,可能的值有红、黄、绿、蓝,而尺码是另一类规格,可能的取值有L、M。那它们的规格组合数为:4*2 = 8,如果再另一类规格是版型,分别为修身和宽松,那就有4 * 2 * 2 = 16种组合了。

数组交叉算法

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
	<script>
		var _attrname = [ "颜色", "尺寸", "套餐","面料"];//版型,品牌等...
		var a = [ "白色", "黑色", "紫色" ];
		//var b = [];
		var b = [ "x", "s", "m" ];
		var c = [ "套餐1", "套餐2" ];
                var d = ["纯棉","涤纶","蚕丝","麻","锦纶","粘胶","羊绒","醋纤"];
		var _attrval = new Array();

		_attrval.push(a);
		_attrval.push(b);
		_attrval.push(c);
                _attrval.push(d);

		getnext('', _attrval);

		function getnext(str, arr) {
			var subA = arr[0];
			var newArr = copyArray(arr);
			if (subA.length > 0) {
				for (var n = 0; n < subA.length; n++) {
					if (newArr) {
						getnext(str + "," + subA[n], newArr);
					} else {
						document.write(str + "," + subA[n]);
						document.write("<br>");
					}
				}
			} else {
				if (newArr) {
					getnext(str, newArr);
				} else {
					document.write(str);
					document.write("<br>");
				}
			}
		}

		function copyArray(arr) {
			if (arr.length > 1) {
				var b = new Array(arr.length - 1);
				for (var i = 1; i < arr.length; i++) {
					b[i - 1] = arr[i];
				}
				return b;
			}
		}
	</script>
</body>
</html>

输出:

,白色,x,套餐1,纯棉
,白色,x,套餐1,涤纶
,白色,x,套餐1,蚕丝
,白色,x,套餐1,麻
,白色,x,套餐1,锦纶
,白色,x,套餐1,粘胶
,白色,x,套餐1,羊绒
,白色,x,套餐1,醋纤
,白色,x,套餐2,纯棉

....