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]
复制代码