<html>
<head>
<title>二維數組排列組合</title>
</head>
<body>
<div id="showDiv"></div>
</body>
<script type="text/javascript"> var arrays = [ ["a0", "a1", "a2", "a3"], ["b0", "b1", "b2"], ["c0","c1","c2","c3", "c4"] ]; var array = getArrayByArrays(arrays); window.document.getElementById('showDiv').innerHTML = '元素個數:' + array.length + '<br /><br />' + array.join('<br />'); /** * 獲取【二維數組】的【排列組合】 */ function getArrayByArrays(arrays) { var arr = [""]; // 初始化第一個內層數組
/** * 遍歷外層數組 */
for (var index = 0; index < arrays.length; index++) { // console.log('外層數組索引 = ' + index);
arr = getValuesByArray(arr, arrays[index]); } return arr; } function getValuesByArray(arr1, arr2) { var arr = []; /** * 遍歷外層數組 */
for (var index = 0; index < arr1.length; index++) { var value1 = arr1[index]; /** * 遍歷內層數組 */
for(var cursor = 0; cursor < arr2.length; cursor++) { var value2 = arr2[cursor]; var value = value1 + ' - ' + value2; arr.push(value); console.log(arr); }; }; return arr; }; </script>
</html>