以下是一种实现方法:

<!DOCTYPE html>
<html>
<head>
	<title>Sort Permutations</title>
</head>
<body>
	<h1>Sort Permutations</h1>
	<div id='output'></div>

	<script>
		// 定义要排序的数组
		var arr = ['a', 'b', 'c', 'd'];
		// 存储所有排列的数组
		var permutations = [];

		// 递归函数,用于生成所有排列
		function generatePermutations(arr, current = []) {
			// 如果当前数组为空,则说明已经取完了所有元素,将当前排列加入结果数组
			 if (arr.length === 0) {
				permutations.push(current);
			} else {
				// 循环遍历剩余的元素,并递归调用自己
				for (var i = 0; i < arr.length; i++) {
					var nextArr = arr.slice(0, i).concat(arr.slice(i + 1));
					generatePermutations(nextArr, current.concat(arr[i]));
				}
			}
		}

		// 生成所有排列
		generatePermutations(arr);

		// 输出所有排列到页面上
		var outputDiv = document.getElementById('output');
		for (var i = 0; i < permutations.length; i++) {
			var permutationStr = permutations[i].join(' ');
			outputDiv.innerHTML += permutationStr + '<br>';
		}
	</script>
</body>
</html>

输出结果如下所示:

a b c d
a b d c
a c b d
a c d b
a d b c
a d c b
b a c d
b a d c
b c a d
b c d a
b d a c
b d c a
c a b d
c a d b
c b a d
c b d a
c d a b
c d b a
d a b c
d a c b
d b a c
d b c a
d c a b
d c b a
JavaScript 生成数组所有排列组合 - 代码示例

原文地址: https://www.cveoy.top/t/topic/nI5P 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录