前端面試必會手寫的程式碼

一諾淺淺發表於2018-05-16

1.物件的深複製

function deepCopy(p, c) {
 	for(var i in p) {
 		if(typeof p[i] === 'object') {
 			c[i] = (p[i].constructor === Array) ? [] :{};
 			deepCopy(p[i], c[i]);
 		} else {
 			c[i] = p[i];
 		}
 	}
 	return c;
 }
 //demo:
 var oldbject = {
 	'title': '今天天氣很好',
 	'hobby': [
 		'籃球',
 		'足球',
 		'乒乓球',
 		'羽毛球'
 	],
 	'list':[{
 		'id':1,
 		'age':28,
 		'xingming':'王小明',
 		'job':'前端開發工程師',
 	},{
 		'id':1,
 		'age':38,
 		'xingming':'李欣然',
 		'job':'java',
 	}]
 }
 var newobject = deepCopy(oldbject);
 console.log(newobject);
 newobject.subtitle = '今天週三';
 
 console.log(newobject);
 console.log(oldbject);
複製程式碼

2.氣泡排序

    function sortA(arr) {
    	for(var i = 0; i < arr.length - 1; i++) {
    		for(var j = i + 1; j < arr.length; j++) {
    			if(arr[i] > arr[j]) {
    				var index = arr[j];
    				arr[j] = arr[i];
    				arr[i] = index;
    			}
    		}
    	}
    	return arr;
    }
    //demo:
    var numarr = [12, 18, 20, 19, 33, 9, 10, 6];
    console.log(sortA(numarr));//[6, 9, 10, 12, 18, 19, 20, 33]
複製程式碼

3.快速排序

function sortB(arr) {
	if(arr.length <= 1) {
		return arr
	} else {
		var len = Math.floor(arr.length / 2);
		var middlenum = arr.splice(len, 1);
		var left = [];
		var right = [];
		for(var i = 0; i < arr.length; i++) {
			if(arr[i] < middlenum) {
				left.push(arr[i])
			} else {
				right.push(arr[i])
			}
		}
	}
	return sortB(left).concat(middlenum,sortB(right));
}
//demo:
console.log( sortB([12,16,20,9,8,17,10,23] )) //[8, 9, 10, 12, 16, 17, 20, 23]	
複製程式碼

4.斐波那契數列 ( 1,1,2,3,5,8... )

function digui(index) {
	if(index < 0) { 
		return 0;
	}
	if(index <= 2) {
		return 1;
	}
	return digui(index - 1) + digui(index - 2);
}
//demo:
console.log(  digui(5) );//5
複製程式碼

5.陣列去重

5.1 利用物件的鍵不能相同去重

function norepeat(arr){
	var obj = {},newarr = [];
	for(var i=0;i<arr.length;i++){
		if(!obj[arr[i]]){
			obj[arr[i]] = 1;
			newarr.push( arr[i] )
		}
	}
	return newarr
}
console.log( norepeat([1,2,1,2,3,3,1,2]) ); //[1,2,3]
複製程式碼

5.2 陣列排序後相鄰去除法

function loop(arr) {
	arr.sort();
	var newarr = [arr[0]];
	for(var i = 0; i < arr.length; i++) {
		if(arr[i] !== newarr[newarr.length - 1]) {
			newarr.push(arr[i]);
		}
	}
	return newarr;
}
console.log(loop([1, 4, 3, 1, 2, 3, 3, 1, 2])); //[1,2,3,4]
複製程式碼

5.3 遍歷陣列用indexOf去重

function fn1(arr) {
	var newarr = [];
	for(var i = 0; i < arr.length; i++) {
		if(newarr.indexOf(arr[i]) == -1) {
			newarr.push(arr[i])
		}
	}
	return newarr;
}
console.log(fn1( [1, 4, 3, 1, 2, 3, 3, 1, 2] ));//[1, 4, 3, 2]
複製程式碼

5.4 ES6提供的方法set

var newa = Array.from( new Set( [1, 4, 3, 1, 2, 3, 3, 1, 2]) );
console.log(newa);//[1, 4, 3, 2]
var newb = [...new Set( [1, 4, 3, 1, 2, 3, 3, 1, 2] )];
console.log(newb); //[1, 4, 3, 2]
複製程式碼

相關文章