1、全排列(递归)

function permutation(arr){
	if (arr.length == 1)
		return arr;
	else if (arr.length == 2)
		return [[arr[0],arr[1]],[arr[1],arr[0]]];
	else {
		var temp = [];
		for (var i = 0; i < arr.length; i++) {
			var save = arr[i];
			arr.splice(i, 1);//取出arr[i]
			var res = permutation(arr);//递归排列arr[0],arr[1],...,arr[i-1],arr[i+1],...,arr[n]
			arr.splice(i, 0, save);//将arr[j]放入数组,保持原来的位置
			for (var j = 0; j < res.length; j++) {
				res[j].push(arr[i]);
				temp.push(res[j]);//将arr[j]组合起来
			}
		}
		return temp;
	}
}

2、数组去重

方法一:

function norepeat(contents) {
	var norepeatContents = [];
	for (var i = 0; i < contents.length; i++) {
		if(norepeatContents.indexOf(contents[i]) == -1)
			norepeatContents.push(contents[i]);
	}
	return norepeatContents;
}

方法二:

function norepeat(contents) {
	var norepeatContents = [], hash = {};
	for (var i = 0; i < contents.length; i++) {
		if(!hash[contents[i]]) {
			norepeatContents.push(contents[i]);
			hash[contents[i]] = true;
		}
	}
	return norepeatContents;
}

3、求数组最大数

方法一:

function findMax(arr) {
	var max = arr[0];
	for (var i = 1; i < arr.length; i++) {
		if (arr[i] > max)
			max = arr[i];
	}
	return max;
}

方法二:

function findMax(arr) {
	return Math.max.apply(Math, arr);
}


本文转载:CSDN博客